更改资源文件的位置
把webapp目录下的文件拷贝到resources目录的static目录下
迁移web.xml
扩展WebApplicationInitializer迁移web.xml
public class WebInitializer implements WebApplicationInitializer {//1
@Override
public void onStartup(ServletContext servletContext)
throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(MyMvcConfig.class);
ctx.setServletContext(servletContext); //2
Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx)); //3
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
servlet.setAsyncSupported(true);//1
}
}
WebApplicationInitializer的实现类会自动被SpringServletContainerInitializer(用来启动servlet3.0容器
)获取到。
EnableWebMvc
开启该注解,会开启一些mvc的默认配置:
必要的ViewResolver,比如ContentNegoti-atingViewResolver和Bean-NameViewRe-solver。
将必要的Converter、GenericConverter和Formatter等bean注册到IoC容器。 - 添加一系列的HttpMessageConverter以便支持对Web请求和相应的类型转换。
自动配置和注册MessageCodesResolver。
但如果使用下面的方式则会覆盖默认的配置(spring-boot-starter-web该依赖会autoconfig这些
)。
自定义webmvc
可以通过Configuration、EnableWebMvc注解在继承WebMvcConfigurerAdapter的类上面,来自定义mvc的配置
@Configuration
@EnableWebMvc// 1
@EnableScheduling
@ComponentScan("com.wisely.highlight_springmvc4")
public class MyMvcConfig extends WebMvcConfigurerAdapter {// 2
@Bean
public InternalResourceViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
return viewResolver;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/assets/**").addResourceLocations(
"classpath:/assets/");// 3
}
@Bean
// 1
public DemoInterceptor demoInterceptor() {
return new DemoInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {// 2
registry.addInterceptor(demoInterceptor());
}
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/index").setViewName("/index");
registry.addViewController("/toUpload").setViewName("/upload");
registry.addViewController("/converter").setViewName("/converter");
registry.addViewController("/sse").setViewName("/sse");
registry.addViewController("/async").setViewName("/async");
}
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
configurer.setUseSuffixPatternMatch(false);
}
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
multipartResolver.setMaxUploadSize(1000000);
return multipartResolver;
}
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(converter());
}
@Bean
public MyMessageConverter converter(){
return new MyMessageConverter();
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。