Struts学习(第三篇)——StrutsPrepareAndExecuteFilter拦截器源码

本文来自:曹胜欢博客专栏。转载请注明出处:http://blog.csdn.net/csh624366188

       

 

       前面博客我们介绍了开发struts2应用程序的基本流程(细谈struts2之开发第一个struts2的实例),通过前面我们知道了struts2实现请求转发和配置文件加载都是拦截器进行的操作,这也就是为什么我们要在web.xml配置struts2的拦截器的原因了。我们知道,在开发struts2应用开发的时候我们要在web.xml进行配置拦截器org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter(在一些老版的一般配置org.apache.struts2.dispatcher.FilterDispatcher),不知道大家刚开始学的时候有没有这个疑问,为什么通过这个拦截器我们就可以拦截到我们提交的请求,并且一些配置文件就可以得到加载呢?不管你有没有,反正我是有。我想这个问题的答案,我们是非常有必要去看一下这个拦截器的源码去找。

打开StrutsPrepareAndExecuteFilter拦截器源码我们可以看出以下类的信息

属性摘要:

Protected        List<Pattern>              excludedPatterns 

protected      ExecuteOperations      execute 
protected      
PrepareOperations       prepare

         我们可以看出StrutsPrepareAndExecuteFilter与普通的Filter并无区别,方法除继承自Filter外,仅有一个回调方法,第三部分我们将按照Filter方法调用顺序,init>doFilter>destroy顺序地分析源码。

提供的方法:

destroy()    

  继承自Filter,用于资源释放

doFilter(ServletRequest req, ServletResponse res, FilterChain chain)

   继承自Filter,执行方法

init(FilterConfig filterConfig)  

继承自Filter,初始化参数

 postInit(Dispatcher dispatcher, FilterConfig filterConfig) 

  Callback for post initialization(一个空的方法,用于方法回调初始化)

下面我们一一对这些方法看一下:

1.init方法:我们先整体看一下这个方法:

 

  1. public void init(FilterConfig filterConfig) throws ServletException {  
  2.   
  3. InitOperations init = new InitOperations();  
  4.   
  5. try {  
  6.   
  7. //封装filterConfig,其中有个主要方法getInitParameterNames将参数名字以String格式存储在List中  
  8.   
  9. FilterHostConfig config = new FilterHostConfig(filterConfig);  
  10.   
  11. // 初始化struts内部日志  
  12.   
  13. init.initLogging(config);  
  14.   
  15. //创建dispatcher ,并初始化,这部分下面我们重点分析,初始化时加载那些资源  
  16.   
  17. Dispatcher dispatcher = init.initDispatcher(config);  
  18.   
  19. init.initStaticContentLoader(config, dispatcher);  
  20.   
  21. //初始化类属性:prepare 、execute  
  22.   
  23. prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher);  
  24.   
  25. execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher);  
  26.   
  27. this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);  
  28.   
  29. //回调空的postInit方法  
  30.   
  31. postInit(dispatcher, filterConfig);  
  32.   
  33. finally {  
  34.   
  35. init.cleanup();  
  36.   
  37. }  
  38.   
  39. }  


      首先开一下FilterHostConfig 这个封装configfilter的类:  这个类总共不超过二三十行代码getInitParameterNames是这个类的核心,将Filter初始化参数名称有枚举类型转为Iterator。此类的主要作为是对filterConfig 封装。具体代码如下:

 

  1. public Iterator<String> getInitParameterNames() {  
  2.   
  3.        return   MakeIterator.convert(config.getInitParameterNames());  
  4.   
  5.    }  

下面咱接着一块看Dispatcher dispatcher = init.initDispatcher(config);这是重点,创建并初始化Dispatcher  ,看一下具体代码:

   

  1. public Dispatcher initDispatcher( HostConfig filterConfig ) {  
  2.   
  3.        Dispatcher dispatcher = createDispatcher(filterConfig);  
  4.   
  5.        dispatcher.init();  
  6.   
  7.        return dispatcher;  
  8.   
  9.    }     
  10.   
  11.   
  12. span style="FONT-SIZE: 18px"><span style="color:#000000;BACKGROUND: rgb(255,255,255)">     </span><span style="color:#000000;BACKGROUND: rgb(255,255,255)"><span style="color:#cc0000;"><strong>创建<span style="font-family:Verdana;">Dispatcher</span><span style="font-family:宋体;">,会读取 </span><span style="font-family:Verdana;">filterConfig </span><span style="font-family:宋体;">中的配置信息,将配置信息解析出来,封装成为一个</span><span style="font-family:Verdana;">Map</span></strong></span><span style="font-family:宋体;">,然后</span></span><span style="color:#000000;BACKGROUND: rgb(255,255,255)">根据</span><span style="color:#000000;BACKGROUND: rgb(255,255,255)">servlet<span style="font-family:宋体;">上下文和参数</span><span style="font-family:Verdana;">Map</span><span style="font-family:宋体;">构造</span><span style="font-family:Verdana;">Dispatcher </span><span style="font-family:宋体;"></span></span></span>  
  1. private Dispatcher createDispatcher( HostConfig filterConfig ) {  
  2.   
  3. Map<String, String> params = new HashMap<String, String>();  
  4.   
  5. for ( Iterator e = filterConfig.getInitParameterNames(); e.hasNext(); ) {  
  6.   
  7. String name = (String) e.next();  
  8.   
  9. String value = filterConfig.getInitParameter(name);  
  10.   
  11. params.put(name, value);  
  12.   
  13. }  
  14.   
  15. return new Dispatcher(filterConfig.getServletContext(), params);  
  16.   
  17. }  


      Dispatcher构造玩以后,开始对他进行初始化,加载struts2的相关配置文件,将按照顺序逐一加载:default.propertiesstruts-default.xml,struts-plugin.xml,struts.xml……我们一起看看他是怎么一步步的加载这些文件的 dispatcher的init()方法:

   

  1. public void init() {  
  2.   
  3.   
  4.     if (configurationManager == null) {  
  5.   
  6.     configurationManager = createConfigurationManager(BeanSelectionProvider.DEFAULT_BEAN_NAME);  
  7.   
  8.     }  
  9.         try {  
  10.   
  11.             init_DefaultProperties(); // [1]  
  12.   
  13.             init_TraditionalXmlConfigurations(); // [2]  
  14.   
  15.             init_LegacyStrutsProperties(); // [3]  
  16.   
  17.             init_CustomConfigurationProviders(); // [5]  
  18.   
  19.             init_FilterInitParameters() ; // [6]  
  20.   
  21.             init_AliasStandardObjects() ; // [7]  
  22.   
  23.   
  24.             Container container = init_PreloadConfiguration();  
  25.   
  26.             container.inject(this);  
  27.   
  28.             init_CheckConfigurationReloading(container);  
  29.   
  30.             init_CheckWebLogicWorkaround(container);  
  31.   
  32.   
  33.             if (!dispatcherListeners.isEmpty()) {  
  34.   
  35.                 for (DispatcherListener l : dispatcherListeners) {  
  36.   
  37.                     l.dispatcherInitialized(this);  
  38.   
  39.                 }  
  40.   
  41.             }  
  42.   
  43.         } catch (Exception ex) {  
  44.   
  45.             if (LOG.isErrorEnabled())  
  46.   
  47.                 LOG.error("Dispatcher initialization failed", ex);  
  48.   
  49.             throw new StrutsException(ex);  
  50.   
  51.         }  
  52.   
  53.     }  


下面我们一起来看一下【1】,【2】,【3】,【5】,【6】的源码,看一下什么都一目了然了:

1.这个方法中是将一个DefaultPropertiesProvider对象追加到ConfigurationManager对象内部的ConfigurationProvider队列中。 DefaultPropertiesProviderregister()方法可以载入org/apache/struts2/default.properties中定义的属性。

  1. try {  
  2.   
  3.            defaultSettings = new PropertiesSettings("org/apache/struts2/default");  
  4.   
  5.        } catch (Exception e) {  
  6.   
  7.            throw new ConfigurationException("Could not find or error in org/apache/struts2/default.properties", e);  
  8.   
  9.        }  


2. 调用init_TraditionalXmlConfigurations()方法,实现载入FilterDispatcher的配置中所定义的config属性。 如果用户没有定义config属性,struts默认会载入DEFAULT_CONFIGURATION_PATHS这个值所代表的xml文件。它的值为"struts-default.xml,struts-plugin.xml,struts.xml"。也就是说框架默认会载入这三个项目xml文件。如果文件类型是XML格式,则按照xwork-x.x.dtd模板进行读取。如果,是Struts的配置文件,则按struts-2.X.dtd模板进行读取。

 private static final String DEFAULT_CONFIGURATION_PATHS = "struts-default.xml,struts-plugin.xml,struts.xml";

3.创建一个LegacyPropertiesConfigurationProvider类,并将它追加到ConfigurationManager对象内部的ConfigurationProvider队列中。LegacyPropertiesConfigurationProvider类载入struts.properties中的配置,这个文件中的配置可以覆盖default.properties中的。其子类是DefaultPropertiesProvider

5.init_CustomConfigurationProviders()此方法处理的是FilterDispatcher的配置中所定义的configProviders属性。负责载入用户自定义的ConfigurationProvider

  1. String configProvs = initParams.get("configProviders");  
  2.   
  3.         if (configProvs != null) {  
  4.   
  5.             String[] classes = configProvs.split("\\s*[,]\\s*");  
  6.   
  7.             for (String cname : classes) {  
  8.   
  9.                 try {  
  10.   
  11.                     Class cls = ClassLoaderUtils.loadClass(cname, this.getClass());  
  12.   
  13.                     ConfigurationProvider prov = (ConfigurationProvider)cls.newInstance();  
  14.   
  15.                     configurationManager.addConfigurationProvider(prov);  
  16.   
  17.                 } catch (InstantiationException e) {  
  18.   
  19.                     throw new ConfigurationException("Unable to instantiate provider: "+cname, e);  
  20.   
  21.                 } catch (IllegalAccessException e) {  
  22.   
  23.                     throw new ConfigurationException("Unable to access provider: "+cname, e);  
  24.   
  25.                 } catch (ClassNotFoundException e) {  
  26.   
  27.                     throw new ConfigurationException("Unable to locate provider class: "+cname, e);  
  28.   
  29.                 }  
  30.   
  31.             }  
  32.   
  33.         }  


6.init_FilterInitParameters()此方法用来处理FilterDispatcher的配置中所定义的所有属性

7. init_AliasStandardObjects(),将一个BeanSelectionProvider类追加到ConfigurationManager对象内部的ConfigurationProvider队列中。BeanSelectionProvider类主要实现加载org/apache/struts2/struts-messages

  1. private void init_AliasStandardObjects() {  
  2.         configurationManager.addConfigurationProvider(  
  3. new BeanSelectionProvider());  
  4. }  



相信看到这大家应该明白了,struts2的一些配置的加载顺序和加载时所做的工作,其实有些地方我也不是理解的很清楚。其他具体的就不在说了,init方法占时先介绍到这

2、doFilter方法

     doFilter是过滤器的执行方法,它拦截提交的HttpServletRequest请求,HttpServletResponse响应,作为strtus2的核心拦截器,在doFilter里面到底做了哪些工作,我们将逐行解读其源码,大体源码如下:

  1. public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {  
  2.   
  3. //父类向子类转:强转为http请求、响应  
  4.   
  5. HttpServletRequest request = (HttpServletRequest) req;  
  6.   
  7. HttpServletResponse response = (HttpServletResponse) res;  
  8.   
  9. try {  
  10.   
  11. //设置编码和国际化  
  12.   
  13. prepare.setEncodingAndLocale(request, response);  
  14.   
  15. //创建Action上下文(重点)  
  16.   
  17. prepare.createActionContext(request, response);  
  18.   
  19. prepare.assignDispatcherToThread();  
  20.   
  21. if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {  
  22.   
  23. chain.doFilter(request, response);  
  24.   
  25. } else {  
  26.   
  27. request = prepare.wrapRequest(request);  
  28.   
  29. ActionMapping mapping = prepare.findActionMapping(request, response, true);  
  30.   
  31. if (mapping == null) {  
  32.   
  33. boolean handled = execute.executeStaticResourceRequest(request, response);  
  34.   
  35. if (!handled) {  
  36.   
  37. chain.doFilter(request, response);  
  38.   
  39. }  
  40.   
  41. } else {  
  42.   
  43. execute.executeAction(request, response, mapping);  
  44.   
  45. }  
  46.   
  47. }  
  48.   
  49. } finally {  
  50.   
  51. prepare.cleanupRequest(request);  
  52.   
  53. }  
  54.   
  55. }  


下面我们就逐句的来的看一下:设置字符编码和国际化很简单prepare调用了setEncodingAndLocale,然后调用了dispatcher方法的prepare方法:

  1. /**  
  2.   
  3. * Sets the request encoding and locale on the response  
  4.   
  5. */  
  6.   
  7. public void setEncodingAndLocale(HttpServletRequest request, HttpServletResponse response) {  
  8.   
  9. dispatcher.prepare(request, response);  
  10.   
  11. }  


看下prepare方法,这个方法很简单只是设置了encoding locale ,做的只是一些辅助的工作:

  1. public void prepare(HttpServletRequest request, HttpServletResponse response) {  
  2.   
  3. String encoding = null;  
  4.   
  5. if (defaultEncoding != null) {  
  6.   
  7. encoding = defaultEncoding;  
  8.   
  9. }  
  10.   
  11. Locale locale = null;  
  12.   
  13. if (defaultLocale != null) {  
  14.   
  15. locale = LocalizedTextUtil.localeFromString(defaultLocale, request.getLocale());  
  16.   
  17. }  
  18.   
  19. if (encoding != null) {  
  20.   
  21. try {  
  22.   
  23. request.setCharacterEncoding(encoding);  
  24.   
  25. } catch (Exception e) {  
  26.   
  27. LOG.error("Error setting character encoding to '" + encoding + "' - ignoring.", e);  
  28.   
  29. }  
  30.   
  31. }  
  32.   
  33. if (locale != null) {  
  34.   
  35. response.setLocale(locale);  
  36.   
  37. }  
  38.   
  39. if (paramsWorkaroundEnabled) {  
  40.   
  41. request.getParameter("foo"); // simply read any parameter (existing or not) to "prime" the request  
  42.   
  43. }  
  44.   
  45. }  


下面咱重点看一下创建Action上下文重点

   Action上下文创建(重点)

       ActionContext是一个容器,这个容易主要存储requestsessionapplicationparameters等相关信息.ActionContext是一个线程的本地变量,这意味着不同的action之间不会共享ActionContext,所以也不用考虑线程安全问题。其实质是一个Mapkey是标示requestsession……的字符串,值是其对应的对象:

static ThreadLocal actionContext = new ThreadLocal();

Map<String, Object> context;

下面我们看起来下创建action上下文的源码

  1. /**  
  2.   
  3. *创建Action上下文,初始化thread local  
  4.   
  5. */  
  6.   
  7. public ActionContext createActionContext(HttpServletRequest request, HttpServletResponse response) {  
  8.   
  9. ActionContext ctx;  
  10.   
  11. Integer counter = 1;  
  12.   
  13. Integer oldCounter = (Integer) request.getAttribute(CLEANUP_RECURSION_COUNTER);  
  14.   
  15. if (oldCounter != null) {  
  16.   
  17. counter = oldCounter + 1;  
  18.   
  19. }  
  20.   
  21.   
  22.   
  23. //注意此处是从ThreadLocal中获取此ActionContext变量  
  24.   
  25. ActionContext oldContext = ActionContext.getContext();  
  26.   
  27. if (oldContext != null) {  
  28.   
  29. // detected existing context, so we are probably in a forward  
  30.   
  31. ctx = new ActionContext(new HashMap<String, Object>(oldContext.getContextMap()));  
  32.   
  33. } else {  
  34.   
  35. ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();  
  36.   
  37. stack.getContext().putAll(dispatcher.createContextMap(request, response, null, servletContext));  
  38.   
  39. //stack.getContext()返回的是一个Map<String,Object>,根据此Map构造一个ActionContext  
  40.   
  41. ctx = new ActionContext(stack.getContext());  
  42.   
  43. }  
  44.   
  45. request.setAttribute(CLEANUP_RECURSION_COUNTER, counter);  
  46.   
  47. //将ActionContext存如ThreadLocal  
  48.   
  49. ActionContext.setContext(ctx);  
  50.   
  51. return ctx;  
  52.   
  53. }  


一句句来看:

ValueStackstack= dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();  

dispatcher.getContainer().getInstance(ValueStackFactory.class)根据字面估计一下就是创建ValueStackFactory的实例。这个地方我也只是根据字面来理解的。ValueStackFactory是接口,其默认实现是OgnlValueStackFactory,调用OgnlValueStackFactorycreateValueStack()

下面看一下OgnlValueStack的构造方法  

  1. protected OgnlValueStack(XWorkConverter xworkConverter, CompoundRootAccessor accessor, TextProvider prov, boolean allowStaticAccess) {     
  2.   
  3.       //new一个CompoundRoot出来    
  4.   
  5.     setRoot(xworkConverter, accessor, new CompoundRoot(), allowStaticAccess);     
  6.   
  7.     push(prov);     
  8.   
  9. }    


接下来看一下setRoot方法:

  1. protected void setRoot(XWorkConverter xworkConverter, CompoundRootAccessor accessor, CompoundRoot compoundRoot,     
  2.   
  3.                        boolean allowStaticMethodAccess) {     
  4.   
  5.     //OgnlValueStack.root = compoundRoot;                    
  6.   
  7.     this.root = compoundRoot;     
  8.   
  9. 1    //方法/属性访问策略。    
  10.   
  11.     this.securityMemberAccess = new SecurityMemberAccess(allowStaticMethodAccess);     
  12.   
  13.     //创建context了,创建context使用的是ongl的默认方式。    
  14.   
  15.     //Ognl.createDefaultContext返回一个OgnlContext类型的实例    
  16.   
  17.     //这个OgnlContext里面,root是OgnlValueStack中的compoundRoot,map是OgnlContext自己创建的private Map _values = new HashMap(23);    
  18.   
  19.     this.context = Ognl.createDefaultContext(this.root, accessor, new OgnlTypeConverterWrapper(xworkConverter), securityMemberAccess);       
  20.   
  21.          
  22.   
  23.      //不是太理解,猜测如下:    
  24.   
  25.     //context是刚刚创建的OgnlContext,其中的HashMap类型_values加入如下k-v:    
  26.   
  27.    //key:com.opensymphony.xwork2.util.ValueStack.ValueStack    
  28.   
  29.     //value:this,这个应该是当前的OgnlValueStack实例。    
  30.   
  31.     //刚刚用断点跟了一下,_values里面是:    
  32.   
  33.     //com.opensymphony.xwork2.ActionContext.container=com.opensymphony.xwork2.inject.ContainerImpl@96231e    
  34.   
  35.     //com.opensymphony.xwork2.util.ValueStack.ValueStack=com.opensymphony.xwork2.ognl.OgnlValueStack@4d912    
  36.   
  37.     context.put(VALUE_STACK, this);     
  38.   
  39.   //此时:OgnlValueStack中的compoundRoot是空的;    
  40.   
  41.    //context是一个OgnlContext,其中的_root指向OgnlValueStack中的root,_values里面的东西,如刚才所述。    
  42.   
  43.     //OgnlContext中的额外设置。    
  44.   
  45.     Ognl.setClassResolver(context, accessor);     
  46.   
  47.     ((OgnlContext) context).setTraceEvaluations(false);     
  48.   
  49.     ((OgnlContext) context).setKeepLastEvaluation(false);     
  50.   
  51. }             
  52.        

  上面代码中dispatcher.createContextMap,如何封装相关参数:,我们以RequestMap为例,其他的原理都一样:主要方法实现:

  1. //map的get实现  
  2.   
  3. public Object get(Object key) {  
  4.   
  5. return request.getAttribute(key.toString());  
  6.   
  7. }  
  8.   
  9. //map的put实现  
  10.   
  11. public Object put(Object key, Object value) {  
  12.   
  13. Object oldValue = get(key);  
  14.   
  15. entries = null;  
  16.   
  17. request.setAttribute(key.toString(), value);  
  18.   
  19. return oldValue;  
  20.   
  21. }  


        到此,几乎StrutsPrepareAndExecuteFilter大部分的源码都涉及到了。自己感觉都好乱,所以还请大家见谅,能力有限,希望大家可以共同学习

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章