Spring 使用 @EnableWebMvc 和 WebMvcConfigurerAdapter 进行静态资源定位的 MVC 配置导致 "forward:" 和 "redirect:" 出现问题

Spring MVC configuration with @EnableWebMvc and WebMvcConfigurerAdapter for static resources location causes problems with "forward:" and "redirect:"

我有一个 Spring 用于 Web 的 Boot hello world 和配置的一些混淆:

Spring版本:1.2.6.RELEASE

我的项目结构:

我需要提供一些静态内容,所以我决定在一些自定义中重新定义此类内容的源目录WebConfig class(用于学习目的):

@EnableWebMvc 的 Javadoc 说:

Adding this annotation to an @Configuration class imports the Spring MVC configuration from WebMvcConfigurationSupport

To customize the imported configuration, implement the interface WebMvcConfigurer or more likely extend the empty method base class WebMvcConfigurerAdapter and override individual methods, e.g.:

于是下一个配置-class诞生了:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/r/**").addResourceLocations("classpath:/static/r/");
        registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/static/r/favicon.ico");
    }
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/r/diploma/index.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }
}

如果 运行 应用并尝试访问 http://localhost:8080/ 我得到下一个例外:

javax.servlet.ServletException: Could not resolve view with name 'forward:/r/diploma/index.html' in servlet with name 'dispatcherServlet'

但是 如果我从我的 WebConfig 中删除 @EnableWebMvc,我会在浏览器中得到我的 index.html。 那么这种行为的原因是什么?

实际上我有一个生产项目,我用它作为研究的例子,它在 WebConfig 上有 @EnableWebMvcWebMvcConfigurerAdapter

你应该添加一个 ViewResolver 来解决你在 WebConfig 中的观点,像这样:

@Bean
public InternalResourceViewResolver defaultViewResolver() {
    return new InternalResourceViewResolver();
}

当您添加 @EnableWebMvc 时,您将关闭所有 spring 启动的网络自动配置,它会自动为您配置此类解析器。通过删除注释,自动配置将再次打开,自动配置ViewResolver解决了问题。