Spring MVC - 返回静态页面

问题描述 投票:0回答:1

我正在努力尝试从 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
,我还应该做什么?

java html servlets spring-mvc controller
1个回答
5
投票

请删除注释

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

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

© www.soinside.com 2019 - 2024. All rights reserved.