web.xml

servlet3.0+规范后,允许servlet,filter,listener不必声明在web.xml中,而是以硬编码的方式存在,实现容器的零配置。

ServletContainerInitializer:启动容器时负责加载相关配置

Java代码  收藏代码
  1. package javax.servlet;  
  2. import java.util.Set;  
  3. public interface ServletContainerInitializer {  
  4.  public void onStartup(Set<Class<?>> c, ServletContext ctx)  
  5.         throws ServletException;   
  6. }  

 容器启动时会自动扫描当前服务中ServletContainerInitializer的实现类,并调用其onStartup方法,其参数Set<Class<?>> c,可通过在实现类上声明注解javax.servlet.annotation.HandlesTypes(xxx.class)注解自动注入,@HandlesTypes会自动扫描项目中所有的xxx.class的实现类,并将其全部注入Set。

 

Spring为其提供了一个实现类:

SpringServletContainerInitializer

 

Java代码  收藏代码
  1. package org.springframework.web;  
  2. import java.lang.reflect.Modifier;  
  3. import java.util.LinkedList;  
  4. import java.util.List;  
  5. import java.util.ServiceLoader;  
  6. import java.util.Set;  
  7. import javax.servlet.ServletContainerInitializer;  
  8. import javax.servlet.ServletContext;  
  9. import javax.servlet.ServletException;  
  10. import javax.servlet.annotation.HandlesTypes;  
  11. import org.springframework.core.annotation.AnnotationAwareOrderComparator;  
  12. @HandlesTypes(WebApplicationInitializer.class)  
  13. public class SpringServletContainerInitializer implements ServletContainerInitializer {  
  14.         @Override  
  15.     public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)  
  16.             throws ServletException {  
  17.   
  18.         List<WebApplicationInitializer> initializers = new LinkedList<WebApplicationInitializer>();  
  19.   
  20.         if (webAppInitializerClasses != null) {  
  21.             for (Class<?> waiClass : webAppInitializerClasses) {  
  22.                 // Be defensive: Some servlet containers provide us with invalid classes,  
  23.                 // no matter what @HandlesTypes says...  
  24.                 if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&  
  25.                         WebApplicationInitializer.class.isAssignableFrom(waiClass)) {  
  26.                     try {  
  27.                         initializers.add((WebApplicationInitializer) waiClass.newInstance());  
  28.                     }  
  29.                     catch (Throwable ex) {  
  30.                         throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);  
  31.                     }  
  32.                 }  
  33.             }  
  34.         }  
  35.   
  36.         if (initializers.isEmpty()) {  
  37.             servletContext.log("No Spring WebApplicationInitializer types detected on classpath");  
  38.             return;  
  39.         }  
  40.   
  41.         AnnotationAwareOrderComparator.sort(initializers);  
  42.         servletContext.log("Spring WebApplicationInitializers detected on classpath: " + initializers);  
  43.   
  44.         for (WebApplicationInitializer initializer : initializers) {  
  45.             initializer.onStartup(servletContext);  
  46.         }  
  47.     }  
  48.   
  49. }  

 

 从中可以看出,WebApplicationInitializer才是我们需要关心的接口,我们只需要将相应的servlet,filter,listener等硬编码到该接口的实现类中即可。比如:

 

xml配置:

 

Xml代码  收藏代码
  1.        <!-- Log4jConfigListener -->  
  2.        <context-param>  
  3.     <param-name>log4jConfigLocation</param-name>  
  4.     <param-value>classpath:config/properties/log4j.properties</param-value>  
  5.        </context-param>  
  6.        <listener>  
  7.     <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  
  8.        </listener>  
  9.   
  10.        <!-- OpenSessionInViewFilter -->  
  11.        <filter>  
  12.     <filter-name>hibernateFilter</filter-name>  
  13.     <filter-class>  
  14.         org.springframework.orm.hibernate4.support.OpenSessionInViewFilter  
  15.     </filter-class>         
  16.        </filter>  
  17.        <filter-mapping>  
  18.     <filter-name>hibernateFilter</filter-name>  
  19.     <url-pattern>/*</url-pattern>  
  20.        </filter-mapping>  
  21.   
  22.        <!-- DemoServlet -->  
  23.        <servlet>  
  24.     <servlet-name>demoServlet</servlet-name>  
  25.     <servlet-class>web.function.servlet.DemoServlet</servlet-class>  
  26.     <load-on-startup>2</load-on-startup>  
  27.        </servlet>  
  28. <servlet-mapping>  
  29.     <servlet-name>demoServlet</servlet-name>  
  30.     <url-pattern>/demo_servlet</url-pattern>  
  31. </servlet-mapping>  

 编码配置:

 

 

Java代码  收藏代码
  1. @Order(1)  
  2. public class CommonInitializer implements WebApplicationInitializer{  
  3.   
  4.     @Override  
  5.     public void onStartup(ServletContext servletContext)  
  6.             throws ServletException {  
  7.           
  8.         //Log4jConfigListener  
  9.         servletContext.setInitParameter("log4jConfigLocation", "classpath:config/properties/log4j.properties");  
  10.         servletContext.addListener(Log4jConfigListener.class);  
  11.           
  12.           
  13.         //OpenSessionInViewFilter  
  14.         OpenSessionInViewFilter hibernateSessionInViewFilter = new OpenSessionInViewFilter();  
  15.         FilterRegistration.Dynamic filterRegistration = servletContext.addFilter(  
  16.                 "hibernateFilter", hibernateSessionInViewFilter);  
  17.         filterRegistration.addMappingForUrlPatterns(  
  18.                 EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE), false, "/");  
  19.           
  20.           
  21.         //DemoServlet  
  22.         DemoServlet demoServlet = new DemoServlet();  
  23.         ServletRegistration.Dynamic dynamic = servletContext.addServlet(  
  24.                 "demoServlet", demoServlet);  
  25.         dynamic.setLoadOnStartup(2);  
  26.         dynamic.addMapping("/demo_servlet");  
  27.                   
  28.           
  29.     }  
  30.   
  31.       
  32. }  

 

Spring为我们提供了一些WebApplicationInitializer的抽象类,我们只需要继承并按需修改即可,比如:

1)org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer : SpringSecurity相关配置

 

xml配置:

 

Xml代码  收藏代码
  1.        <listener>  
  2.     <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>  
  3. </listener>  
  4.   
  5.        <filter>  
  6.     <filter-name>springSecurityFilterChain</filter-name>  
  7.     <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
  8. </filter>  
  9.   
  10.        <filter-mapping>  
  11.     <filter-name>springSecurityFilterChain</filter-name>  
  12.     <url-pattern>/*</url-pattern>  
  13. </filter-mapping>  

 

 

编码配置:

 

Java代码  收藏代码
  1. @Order(2)  
  2. public class WebAppSecurityInitializer  extends AbstractSecurityWebApplicationInitializer   
  3. {  
  4.     //servletContext.addListener("org.springframework.security.web.session.HttpSessionEventPublisher");  
  5.     //session监听器  
  6.     @Override  
  7.     protected boolean enableHttpSessionEventPublisher() {  
  8.         return true;  
  9.     }  
  10. }  

 

2)org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer:MVC相关配置,比如加载spring配置文件,声明DispatcherServlet等等,参看下面的对比:

xml配置:

 

Xml代码  收藏代码
  1.        <context-param>  
  2.     <param-name>contextConfigLocation</param-name>  
  3.     <param-value>  
  4.     classpath:config/context/applicationContext-AppConfig.xml,  
  5.     classpath:config/context/applicationContext-SpringSecurityConfig.xml  
  6.         </param-value>  
  7. </context-param>  
  8.   
  9.        <listener>  
  10.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  11. </listener>  
  12.   
  13.        <filter>  
  14.     <filter-name>Set Character Encoding</filter-name>  
  15.     <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
  16.     <init-param>  
  17.         <param-name>encoding</param-name>  
  18.         <param-value>UTF-8</param-value>  
  19.     </init-param>  
  20.     <init-param>  
  21.         <param-name>forceEncoding</param-name>  
  22.         <param-value>true</param-value>  
  23.     </init-param>  
  24. </filter>  
  25.   
  26.        <filter-mapping>  
  27.     <filter-name>Set Character Encoding</filter-name>  
  28.     <url-pattern>/*</url-pattern>  
  29. </filter-mapping>  
  30.   
  31.        <servlet>  
  32.     <servlet-name>webmvc</servlet-name>  
  33.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  34.     <init-param>  
  35.         <param-name>contextConfigLocation</param-name>  
  36.         <param-value>classpath:config/context/applicationContext-MvcConfig.xml</param-value>  
  37.     </init-param>  
  38.     <load-on-startup>1</load-on-startup>  
  39. </servlet>  
  40.   
  41. <servlet-mapping>  
  42.     <servlet-name>webmvc</servlet-name>  
  43.     <url-pattern>/</url-pattern>  
  44. </servlet-mapping>  

编码方式:

 

 

Java代码  收藏代码
  1. @Order(3)  
  2. //spring DispatcherServlet的配置,其它servlet和监听器等需要额外声明,用@Order注解设定启动顺序  
  3. public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {  
  4.     /* 
  5.       * DispatcherServlet的映射路径 
  6.       */  
  7.     @Override  
  8.     protected String[] getServletMappings() {  
  9.         return new String[]{"/"};  
  10.     }  
  11.    
  12.     /* 
  13.       * 应用上下文,除web部分 
  14.       */  
  15.     @SuppressWarnings({ "unchecked", "rawtypes" })  
  16.     @Override  
  17.     protected Class[] getRootConfigClasses() {  
  18.         //加载配置文件类,这里与上面的xml配置是对应的,需要使用@Configuration注解进行标注,稍后介绍  
  19.         return new Class[] {AppConfig.class, SpringSecurityConfig.class};  
  20.     }  
  21.    
  22.     /* 
  23.       * web上下文 
  24.       */  
  25.     @SuppressWarnings({ "unchecked", "rawtypes" })  
  26.     @Override  
  27.     protected Class[] getServletConfigClasses() {  
  28.         return new Class[] {MvcConfig.class};  
  29.     }  
  30.    
  31.     /* 
  32.       * 注册过滤器,映射路径与DispatcherServlet一致,路径不一致的过滤器需要注册到另外的WebApplicationInitializer中 
  33.       */  
  34.     @Override  
  35.     protected Filter[] getServletFilters() {  
  36.         CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();  
  37.         characterEncodingFilter.setEncoding("UTF-8");  
  38.         characterEncodingFilter.setForceEncoding(true);  
  39.         return new Filter[] {characterEncodingFilter};  
  40.     }     
  41.   
  42. }  

 

posted @ 2016-08-12 14:01  Study_Work  阅读(392)  评论(0编辑  收藏  举报