Ale*_*sky 3 java configuration spring spring-mvc spring-boot
我有一个针对Web的Spring Boot hello world和一些配置混乱:
春季版:1.2.6.RELEASE
我的项目结构:
我需要提供一些静态内容,所以我决定在某些自定义WebConfig类中重新定义此类内容的源目录(用于学习目的):
Javadoc @EnableWebMvc说:
将此批注添加到@Configuration类可从WebMvcConfigurationSupport导入Spring MVC配置
要自定义导入的配置,请实现接口WebMvcConfigurer,或者更可能扩展空方法基类WebMvcConfigurerAdapter并覆盖单个方法,例如:
所以下一个配置类诞生了:
@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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果运行应用程序并尝试访问http:// localhost:8080 / 我得到下一个异常:
javax.servlet.ServletException: Could not resolve view with name 'forward:/r/diploma/index.html' in servlet with name 'dispatcherServlet'
Run Code Online (Sandbox Code Playgroud)
但是,如果我@EnableWebMvc从我的WebConfig中删除,我在浏览器中得到了我的index.html.那么这种行为的原因是什么?
其实我有我使用为例来研究生产项目,它既有@EnableWebMvc与WebMvcConfigurerAdapter上WebConfig.
您应该添加一个ViewResolver来解析您的视图WebConfig,如下所示:
@Bean
public InternalResourceViewResolver defaultViewResolver() {
return new InternalResourceViewResolver();
}
Run Code Online (Sandbox Code Playgroud)
当您添加时@EnableWebMvc,您将关闭所有弹簧启动的Web自动配置,这会自动为您配置这样的解析器.通过删除注释,自动配置将再次打开,自动配置将ViewResolver解决问题.
| 归档时间: |
|
| 查看次数: |
2830 次 |
| 最近记录: |