容器一开始自动加载的配置:相当于web.xml
package config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.MultipartConfigElement;
import javax.servlet.ServletRegistration;
public class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebMvcConfig.class};
}
@Override
protected String[] getServletMappings() {//将请求映射到DispatcherServlet上
return new String[]{"/"};
}
@Override//通过重载,可以对DispatcherServlet进行额外的设置
protected void customizeRegistration(ServletRegistration.Dynamic registration) {
registration.setMultipartConfig(
new MultipartConfigElement("D:\springuploads")
);
}
}
springmvc 部分的配置
@Configuration
@EnableWebMvc
@ComponentScan("Controller")
public class WebMvcConfig extends WebMvcConfigurerAdapter {
//配置视图解析器
@Bean
public ViewResolver viewResolver(){
InternalResourceViewResolver resolver=new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setExposeContextBeansAsAttributes(true);
resolver.setViewClass(JstlView.class);
return resolver;
}
@Override
public void configureDefaultServletHandling(
DefaultServletHandlerConfigurer configurer) {
configurer.enable();//对静态资源的请求转发到servlet容器默认的servlet上
//而不是使用dispatcherServlet来处理
}
}
spring bean 部分的配置
package config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@ComponentScan(
basePackages = {"bean"},
excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION,
value = EnableWebMvc.class)
}
)
public class RootConfig {
}