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方法:我们先整体看一下这个方法:

[java] view plaincopyprint?

  1. public void init(FilterConfig filterConfig) throws ServletException {

  2. InitOperations init = new InitOperations();

  3. try {

  4. //封装filterConfig,其中有个主要方法getInitParameterNames将参数名字以String格式存储在List中

  5. FilterHostConfig config = new FilterHostConfig(filterConfig);

  6. // 初始化struts内部日志

  7. init.initLogging(config);

  8. //创建dispatcher ,并初始化,这部分下面我们重点分析,初始化时加载那些资源

  9. Dispatcher dispatcher = init.initDispatcher(config);

  10. init.initStaticContentLoader(config, dispatcher);

  11. //初始化类属性:prepare 、execute

  12. prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher);

  13. execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher);

  14. this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);

  15. //回调空的postInit方法

  16. postInit(dispatcher, filterConfig);

  17. } finally {

  18. init.cleanup();

  19. }

  20. }


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

[java] view plaincopyprint?

  1. public Iterator<String> getInitParameterNames() {

  2. return MakeIterator.convert(config.getInitParameterNames());

  3. }

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

[html] view plaincopyprint?

  1. public Dispatcher initDispatcher( HostConfig filterConfig ) {

  2. Dispatcher dispatcher = createDispatcher(filterConfig);

  3. dispatcher.init();

  4. return dispatcher;

  5. }

  6. 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>

[java] view plaincopyprint?

  1. private Dispatcher createDispatcher( HostConfig filterConfig ) {

  2. Map<String, String> params = new HashMap<String, String>();

  3. for ( Iterator e = filterConfig.getInitParameterNames(); e.hasNext(); ) {

  4. String name = (String) e.next();

  5. String value = filterConfig.getInitParameter(name);

  6. params.put(name, value);

  7. }

  8. return new Dispatcher(filterConfig.getServletContext(), params);

  9. }


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

[html] view plaincopyprint?

  1. public void init() {

  2. if (configurationManager == null) {

  3. configurationManager = createConfigurationManager(BeanSelectionProvider.DEFAULT_BEAN_NAME);

  4. }

  5. try {

  6. init_DefaultProperties(); // [1]

  7. init_TraditionalXmlConfigurations(); // [2]

  8. init_LegacyStrutsProperties(); // [3]

  9. init_CustomConfigurationProviders(); // [5]

  10. init_FilterInitParameters() ; // [6]

  11. init_AliasStandardObjects() ; // [7]

  12. Container container = init_PreloadConfiguration();

  13. container.inject(this);

  14. init_CheckConfigurationReloading(container);

  15. init_CheckWebLogicWorkaround(container);

  16. if (!dispatcherListeners.isEmpty()) {

  17. for (DispatcherListener l : dispatcherListeners) {

  18. l.dispatcherInitialized(this);

  19. }

  20. }

  21. } catch (Exception ex) {

  22. if (LOG.isErrorEnabled())

  23. LOG.error("Dispatcher initialization failed", ex);

  24. throw new StrutsException(ex);

  25. }

  26. }


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

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

[html] view plaincopyprint?

  1. try {

  2. defaultSettings = new PropertiesSettings("org/apache/struts2/default");

  3. } catch (Exception e) {

  4. throw new ConfigurationException("Could not find or error in org/apache/struts2/default.properties", e);

  5. }


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。

[html] view plaincopyprint?

  1. String configProvs = initParams.get("configProviders");

  2. if (configProvs != null) {

  3. String[] classes = configProvs.split("\s*[,]\s*");

  4. for (String cname : classes) {

  5. try {

  6. Class cls = ClassLoaderUtils.loadClass(cname, this.getClass());

  7. ConfigurationProvider prov = (ConfigurationProvider)cls.newInstance();

  8. configurationManager.addConfigurationProvider(prov);

  9. } catch (InstantiationException e) {

  10. throw new ConfigurationException("Unable to instantiate provider: "+cname, e);

  11. } catch (IllegalAccessException e) {

  12. throw new ConfigurationException("Unable to access provider: "+cname, e);

  13. } catch (ClassNotFoundException e) {

  14. throw new ConfigurationException("Unable to locate provider class: "+cname, e);

  15. }

  16. }

  17. }


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

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

[html] view plaincopyprint?

  1. private void init_AliasStandardObjects() {

  2. configurationManager.addConfigurationProvider(

  3. new BeanSelectionProvider());

  4. }



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

2、doFilter方法

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

[html] view plaincopyprint?

  1. public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

  2. //父类向子类转:强转为http请求、响应

  3. HttpServletRequest request = (HttpServletRequest) req;

  4. HttpServletResponse response = (HttpServletResponse) res;

  5. try {

  6. //设置编码和国际化

  7. prepare.setEncodingAndLocale(request, response);

  8. //创建Action上下文(重点)

  9. prepare.createActionContext(request, response);

  10. prepare.assignDispatcherToThread();

  11. if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {

  12. chain.doFilter(request, response);

  13. } else {

  14. request = prepare.wrapRequest(request);

  15. ActionMapping mapping = prepare.findActionMapping(request, response, true);

  16. if (mapping == null) {

  17. boolean handled = execute.executeStaticResourceRequest(request, response);

  18. if (!handled) {

  19. chain.doFilter(request, response);

  20. }

  21. } else {

  22. execute.executeAction(request, response, mapping);

  23. }

  24. }

  25. } finally {

  26. prepare.cleanupRequest(request);

  27. }

  28. }


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

[html] view plaincopyprint?

  1. /**

  2. * Sets the request encoding and locale on the response

  3. */

  4. public void setEncodingAndLocale(HttpServletRequest request, HttpServletResponse response) {

  5. dispatcher.prepare(request, response);

  6. }


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

[html] view plaincopyprint?

  1. public void prepare(HttpServletRequest request, HttpServletResponse response) {

  2. String encoding = null;

  3. if (defaultEncoding != null) {

  4. encoding = defaultEncoding;

  5. }

  6. Locale locale = null;

  7. if (defaultLocale != null) {

  8. locale = LocalizedTextUtil.localeFromString(defaultLocale, request.getLocale());

  9. }

  10. if (encoding != null) {

  11. try {

  12. request.setCharacterEncoding(encoding);

  13. } catch (Exception e) {

  14. LOG.error("Error setting character encoding to '" + encoding + "' - ignoring.", e);

  15. }

  16. }

  17. if (locale != null) {

  18. response.setLocale(locale);

  19. }

  20. if (paramsWorkaroundEnabled) {

  21. request.getParameter("foo"); // simply read any parameter (existing or not) to "prime" the request

  22. }

  23. }


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

Action上下文创建(重点)

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

static ThreadLocal actionContext = new ThreadLocal();

Map<String, Object> context;

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

[html] view plaincopyprint?

  1. /**

  2. *创建Action上下文,初始化thread local

  3. */

  4. public ActionContext createActionContext(HttpServletRequest request, HttpServletResponse response) {

  5. ActionContext ctx;

  6. Integer counter = 1;

  7. Integer oldCounter = (Integer) request.getAttribute(CLEANUP_RECURSION_COUNTER);

  8. if (oldCounter != null) {

  9. counter = oldCounter + 1;

  10. }

  11. //注意此处是从ThreadLocal中获取此ActionContext变量

  12. ActionContext oldContext = ActionContext.getContext();

  13. if (oldContext != null) {

  14. // detected existing context, so we are probably in a forward

  15. ctx = new ActionContext(new HashMap<String, Object>(oldContext.getContextMap()));

  16. } else {

  17. ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();

  18. stack.getContext().putAll(dispatcher.createContextMap(request, response, null, servletContext));

  19. //stack.getContext()返回的是一个Map<String,Object>,根据此Map构造一个ActionContext

  20. ctx = new ActionContext(stack.getContext());

  21. }

  22. request.setAttribute(CLEANUP_RECURSION_COUNTER, counter);

  23. //将ActionContext存如ThreadLocal

  24. ActionContext.setContext(ctx);

  25. return ctx;

  26. }


一句句来看:

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

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

下面看一下OgnlValueStack的构造方法

[html] view plaincopyprint?

  1. protected OgnlValueStack(XWorkConverter xworkConverter, CompoundRootAccessor accessor, TextProvider prov, boolean allowStaticAccess) {

  2. //new一个CompoundRoot出来

  3. setRoot(xworkConverter, accessor, new CompoundRoot(), allowStaticAccess);

  4. push(prov);

  5. }


接下来看一下setRoot方法:

[html] view plaincopyprint?

  1. protected void setRoot(XWorkConverter xworkConverter, CompoundRootAccessor accessor, CompoundRoot compoundRoot,

  2. boolean allowStaticMethodAccess) {

  3. //OgnlValueStack.root = compoundRoot;

  4. this.root = compoundRoot;

  5. 1 //方法/属性访问策略。

  6. this.securityMemberAccess = new SecurityMemberAccess(allowStaticMethodAccess);

  7. //创建context了,创建context使用的是ongl的默认方式。

  8. //Ognl.createDefaultContext返回一个OgnlContext类型的实例

  9. //这个OgnlContext里面,root是OgnlValueStack中的compoundRoot,map是OgnlContext自己创建的private Map _values = new HashMap(23);

  10. this.context = Ognl.createDefaultContext(this.root, accessor, new OgnlTypeConverterWrapper(xworkConverter), securityMemberAccess);

  11. //不是太理解,猜测如下:

  12. //context是刚刚创建的OgnlContext,其中的HashMap类型_values加入如下k-v:

  13. //key:com.opensymphony.xwork2.util.ValueStack.ValueStack

  14. //value:this,这个应该是当前的OgnlValueStack实例。

  15. //刚刚用断点跟了一下,_values里面是:

  16. //com.opensymphony.xwork2.ActionContext.container=com.opensymphony.xwork2.inject.ContainerImpl@96231e

  17. //com.opensymphony.xwork2.util.ValueStack.ValueStack=com.opensymphony.xwork2.ognl.OgnlValueStack@4d912

  18. context.put(VALUE_STACK, this);

  19. //此时:OgnlValueStack中的compoundRoot是空的;

  20. //context是一个OgnlContext,其中的_root指向OgnlValueStack中的root,_values里面的东西,如刚才所述。

  21. //OgnlContext中的额外设置。

  22. Ognl.setClassResolver(context, accessor);

  23. ((OgnlContext) context).setTraceEvaluations(false);

  24. ((OgnlContext) context).setKeepLastEvaluation(false);

  25. }

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

[html] view plaincopyprint?

  1. //map的get实现

  2. public Object get(Object key) {

  3. return request.getAttribute(key.toString());

  4. }

  5. //map的put实现

  6. public Object put(Object key, Object value) {

  7. Object oldValue = get(key);

  8. entries = null;

  9. request.setAttribute(key.toString(), value);

  10. return oldValue;

  11. }


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

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

原文地址:https://www.cnblogs.com/jgig11/p/4162197.html