Spring MVC - 返回静态页面

时间:2013-06-14 19:43:44

标签: java html servlets spring-mvc controller

我正在努力尝试从spring MVC控制器返回一个静态网页。 我遵循了本教程:http://www.tutorialspoint.com/spring/spring_static_pages_example.htm但它仍然无效。

这是我定义配置(使用的配置类)的方式:

@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;
    }
}

控制器方法:

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

在webapp文件夹下有一个名为“resources”的文件夹,下面有一个文件“Post.html”。我还应该做些什么才能将此页面作为HTML返回,而不是获取字符串“resources / Post.html”?

感谢您的帮助。

1 个答案:

答案 0 :(得分:5)

请删除注释@ResponseBody。删除注释后,应将浏览器重定向到所需的页面。

此注释指示控制器中方法返回的值应绑定到Web响应正文。在您的情况下,您不需要:您需要Spring来呈现页面/resources/Post.html,因此不需要这个注释。