2

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

谢谢您的帮助。

4

1 回答 1

5

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

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

于 2013-06-14T20:01:09.153 回答