【问题标题】:Spring MVC - Return static pageSpring MVC - 返回静态页面
【发布时间】:2013-06-11 13:17:25
【问题描述】:

我正在努力尝试从 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】:

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

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

    【讨论】:

    • 非常感谢!!这就是答案。我现在遇到静态图像问题。但这是另一个问题的主题:)
    猜你喜欢
    • 2017-07-24
    • 1970-01-01
    • 2016-08-09
    • 2013-05-23
    • 2016-10-23
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多