1.实现AbstractAnnotationConfigDispatcherServletInitializer接口,在servlet3.0中web.xml启动时会检测该接口实现类
package org.springframework.source.config; import org.springframework.web.filter.CharacterEncodingFilter; import org.springframework.web.filter.DelegatingFilterProxy; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; import javax.servlet.*; public class WebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { //指定开始被servlet处理的url,配置从/开始 @Override protected String[] getServletMappings() { return new String[]{"/"}; } //配置root上下文,如Jpa数据源等等的配置 @Override protected Class<?>[] getRootConfigClasses() { return new Class<?>[] {ApplicationConfig.class,JpaConfig.class,SecurityConfig.class}; } //配置dispatcher servlet,如果在root config指定了该转发规则就可以忽略 @Override protected Class<?>[] getServletConfigClasses() { return new Class<?>[] {WebMvcConfig.class}; } //配置servlet过滤器 @Override protected Filter[] getServletFilters() { CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter(); characterEncodingFilter.setEncoding("UTF-8"); characterEncodingFilter.setForceEncoding(true); DelegatingFilterProxy securityFilterChain = new DelegatingFilterProxy("springSecurityFilterChain"); return new Filter[] {characterEncodingFilter,securityFilterChain}; } //当registerDispatcherServlet完成时自定义registration @Override protected void customizeRegistration(ServletRegistration.Dynamic registration) { registration.setInitParameter("defaultHtmlEscape","true"); registration.setInitParameter("spring.profiles.active","default"); } }官方doc
Base class forWebApplicationInitializer
implementations that register aDispatcherServletconfigured with annotated classes
很清楚吧,我们要他来register aDispatcherServlet,他会在web启动时被系统扫秒到并配置我们的servlet转发规则及web的上下文
或者你可以使用已经包含该接口的@H_502_27@WebApplicationInitializer
Interface to be implemented in Servlet 3.0+ environments in order to configure the ServletContext programmatically -- as opposed to (or possibly in conjunction with) the traditional web.xml-based approach. Implementations of this SPI will be detected automatically by SpringServletContainerInitializer,which itself is bootstrapped automatically by any Servlet 3.0 container. See its Javadoc for details on this bootstrapping mechanism.2.实现该接口时的最重要的两个
dispatcher servlet
RootConfigClasses3.两个就不多说了
4.现在看看web.xml的配置,很简单吧
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0"> <!-- Map all errors to Spring MVC handler method. See CustomErrorController.generalError() --> <error-page> <location>/generalError</location> </error-page> </web-app>