Java Spring MVC配置中的@EnableWebMvc和WebMVCConfigureAdapter用于静态资源位置会导致出现问题;转发:“;及;重定向:“;
我有一个Spring Boot hello world for web和一些配置混乱: Spring版本:1.2.6.0版本 我的项目结构: 我需要提供一些静态内容,因此我决定在一些自定义Java Spring MVC配置中的@EnableWebMvc和WebMVCConfigureAdapter用于静态资源位置会导致出现问题;转发:“;及;重定向:“;,java,spring,spring-mvc,configuration,spring-boot,Java,Spring,Spring Mvc,Configuration,Spring Boot,我有一个Spring Boot hello world for web和一些配置混乱: Spring版本:1.2.6.0版本 我的项目结构: 我需要提供一些静态内容,因此我决定在一些自定义WebConfig类中重新定义此类内容的源目录(用于学习目的): Javadoc for@EnableWebMvc说: 将此注释添加到@Configuration类将导入Spring 来自WebMvcConfigurationSupport的MVC配置 要自定义导入的配置,请实现接口 WebMVCConfig
WebConfig
类中重新定义此类内容的源目录(用于学习目的):
Javadoc for@EnableWebMvc
说:
将此注释添加到@Configuration类将导入Spring
来自WebMvcConfigurationSupport的MVC配置
要自定义导入的配置,请实现接口
WebMVCConfiguer或更可能扩展空方法基类
WebMVCConfigureAdapter和重写单个方法,例如:
于是,下一个配置类诞生了:
@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);
}
}
如果运行应用程序并尝试访问
我得到了下一个例外:
javax.servlet.ServletException: Could not resolve view with name 'forward:/r/diploma/index.html' in servlet with name 'dispatcherServlet'
但是如果我从我的网络配置中删除@EnableWebMvc
,我会在浏览器中获得index.html。
那么,这种行为的原因是什么呢
实际上,我有一个生产项目,我用它作为例子来研究,它在
WebConfig
上既有@EnableWebMvc
又有webmvcconfigureadapter
,你应该添加viewsolver
来解析WebConfig
中的视图,类似这样:
@Bean
public InternalResourceViewResolver defaultViewResolver() {
return new InternalResourceViewResolver();
}
当您添加@EnableWebMvc
时,您关闭了spring boot的所有web自动配置,它会自动为您配置这样的解析器。通过删除注释,自动配置将再次启用,自动配置的viewsolver
解决了此问题