2

I'm struggling with trying to return a static web page from a spring MVC controller. I followed this tutorial: http://www.tutorialspoint.com/spring/spring_static_pages_example.htm and yet it still isn't working.

This is how I defined the configuration (used configuration class):

@Configuration
@EnableWebMvc
@EnableTransactionManagement
@ComponentScan({ "com.my.web.api"})
@ImportResource("classpath:db-context.xml")
public class ApiServletConfig extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver internalResourceViewResolver = new InternalResourceViewResolver();
        internalResourceViewResolver.setPrefix("/resources/");
        internalResourceViewResolver.setSuffix("*.html");
        return internalResourceViewResolver;
    }
}

The controller method:

@RequestMapping(value = "/{id}/view", method = RequestMethod.GET, produces = "text/html")
@ResponseBody
public String getPostByIdHtml( @PathVariable String id) throws IOException {
    return "/resources/Post.html";
}

Under the webapp folder there's a folder named resources and under which there's a file Post.html. What else should I do in order to get this page returned as HTML instead of getting the string resources/Post.html?

1 Answer 1

5

Please remove the annotation @ResponseBody. Your browser should be redirected to the desired page once the annotation is removed.

This annotation indicates that the value returned by a method in your controller should be bound to the web response body. In your case, you do not need that: you need Spring to render page /resources/Post.html, so no need for this annotation.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot!! That was the answer. I'm having problems with the static images now. But that's a topic for a different question :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.