spring-mvccontrollerstatic-pages

Spring MVC - Return static page


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?


Solution

  • 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.