Struts2源码分析--请求处理(大侠啊 跪拜了)

(s2-048)Struts2 反序列化漏洞 Struts2 Struts2是一个基于MVC设计模式(java)的Web应用框架,它本质上相当于一个servlet,在MVC设计模式中,Struts2作为控制器(Controller)来建立模型与视图的数据交互。Struts2 是 Apache 软件组织推出的一个相当强大的 Java Web 开源框架,本质上相当于一个 servlet。Struts2 基于 MVC 架构,框架结构清晰。通常作为控制器(Controller)来建立模型与视图的数据交互,用于创建企业级 Java web 应用程序。 漏洞复现 阅读详情
Struts2架构图

        请求首先通过Filter chain,Filter主要包括ActionContextCleanUp,它主要清理当前线程的ActionContext和Dispatcher;FilterDispatcher主要通过AcionMapper来决定需要调用哪个Action。
        ActionMapper取得了ActionMapping后,在Dispatcher的serviceAction方法里创建ActionProxy,ActionProxy创建ActionInvocation,然后ActionInvocation调用Interceptors,执行Action本身,创建Result并返回,当然,如果要在返回之前做些什么,可以实现PreResultListener。

Struts2部分类介绍
这部分从Struts2参考文档中翻译就可以了。
ActionMapper
        ActionMapper其实是HttpServletRequest和Action调用请求的一个映射,它屏蔽了Action对于Request等java Servlet类的依赖。Struts2中它的默认实现类是DefaultActionMapper,ActionMapper很大的用处可以根据自己的需要来设计url格式,它自己也有Restful的实现,具体可以参考文档的docs\actionmapper.html。
ActionProxy&ActionInvocation
        Action的一个代理,由ActionProxyFactory创建,它本身不包括Action实例,默认实现DefaultActionProxy是由ActionInvocation持有Action实例。ActionProxy作用是如何取得Action,无论是本地还是远程。而ActionInvocation的作用是如何执行Action,拦截器的功能就是在ActionInvocation中实现的。
ConfigurationProvider&Configuration
        ConfigurationProvider就是Struts2中配置文件的解析器,Struts2中的配置文件主要是尤其实现类XmlConfigurationProvider及其子类StrutsXmlConfigurationProvider来解析,

Struts2请求流程
1、客户端发送请求
2、请求先通过ActionContextCleanUp-->FilterDispatcher
3、FilterDispatcher通过ActionMapper来决定这个Request需要调用哪个Action
4、如果ActionMapper决定调用某个Action,FilterDispatcher把请求的处理交给ActionProxy,这儿已经转到它的Delegate--Dispatcher来执行
5、ActionProxy根据ActionMapping和ConfigurationManager找到需要调用的Action类
6、ActionProxy创建一个ActionInvocation的实例
7、ActionInvocation调用真正的Action,当然这涉及到相关拦截器的调用
8、Action执行完毕,ActionInvocation创建Result并返回,当然,如果要在返回之前做些什么,可以实现PreResultListener。添加PreResultListener可以在Interceptor中实现,不知道其它还有什么方式?

Struts2(2.1.2)部分源码阅读
     从org.apache.struts2.dispatcher.FilterDispatcher开始
     // 创建Dispatcher,此类是一个Delegate,它是真正完成根据url解析,读取对应Action的地方
     public   void  init(FilterConfig filterConfig)  throws  ServletException {
        
try  {
            
this .filterConfig  =  filterConfig;

            initLogging();

            dispatcher 
=  createDispatcher(filterConfig);
            dispatcher.init();
            dispatcher.getContainer().inject(
this );
            
// 读取初始参数pakages,调用parse(),解析成类似/org/apache/struts2/static,/template的数组
            String param  =  filterConfig.getInitParameter( " packages " );
            String packages 
=   " org.apache.struts2.static template org.apache.struts2.interceptor.debugging " ;
            
if  (param  !=   null ) {
                packages 
=  param  +   "   "   +  packages;
            }
            
this .pathPrefixes  =  parse(packages);
        } 
finally  {
            ActionContext.setContext(
null );
        }
    }
     顺着流程我们看Disptcher的init方法。init方法里就是初始读取一些配置文件等,先看init_DefaultProperties,主要是读取properties配置文件。
     private   void  init_DefaultProperties() {
        configurationManager.addConfigurationProvider(
new  DefaultPropertiesProvider());
    }
    打开DefaultPropertiesProvider
     public   void  register(ContainerBuilder builder, LocatableProperties props)
            
throws  ConfigurationException {
        
        Settings defaultSettings 
=   null ;
        
try  {
            defaultSettings 
=   new  PropertiesSettings( " org/apache/struts2/default " );
        } 
catch  (Exception e) {
            
throw   new  ConfigurationException( " Could not find or error in org/apache/struts2/default.properties " , e);
        }
        
        loadSettings(props, defaultSettings);
    }

    
// PropertiesSettings
    
// 读取org/apache/struts2/default.properties的配置信息,如果项目中需要覆盖,可以在classpath里的struts.properties里覆写
     public  PropertiesSettings(String name) {
        
        URL settingsUrl 
=  ClassLoaderUtils.getResource(name  +   " .properties " , getClass());
        
        
if  (settingsUrl  ==   null ) {
            LOG.debug(name 
+   " .properties missing " );
            settings 
=   new  LocatableProperties();
            
return ;
        }
        
        settings 
=   new  LocatableProperties( new  LocationImpl( null , settingsUrl.toString()));

        
//  Load settings
        InputStream in  =   null ;
        
try  {
            in 
=  settingsUrl.openStream();
            settings.load(in);
        } 
catch  (IOException e) {
            
throw   new  StrutsException( " Could not load  "   +  name  +   " .properties: "   +  e, e);
        } 
finally  {
            
if (in  !=   null ) {
                
try  {
                    in.close();
                } 
catch (IOException io) {
                    LOG.warn(
" Unable to close input stream " , io);
                }
            }
        }
    }
    再来看init_TraditionalXmlConfigurations方法,这个是读取struts-default.xml和Struts.xml的方法。
     private   void  init_TraditionalXmlConfigurations() {
        
// 首先读取web.xml中的config初始参数值
        
// 如果没有配置就使用默认的"struts-default.xml,struts-plugin.xml,struts.xml",
        
// 这儿就可以看出为什么默认的配置文件必须取名为这三个名称了
        
// 如果不想使用默认的名称,直接在web.xml中配置config初始参数即可
        String configPaths  =  initParams.get( " config " );
        
if  (configPaths  ==   null ) {
            configPaths 
=  DEFAULT_CONFIGURATION_PATHS;
        }
        String[] files 
=  configPaths.split( " \\s*[,]\\s* " );
        
// 依次解析配置文件,xwork.xml单独解析
         for  (String file : files) {
            
if  (file.endsWith( " .xml " )) {
                
if  ( " xwork.xml " .equals(file)) {
                    configurationManager.addConfigurationProvider(
new  XmlConfigurationProvider(file,  false ));
                } 
else  {
                    configurationManager.addConfigurationProvider(
new  StrutsXmlConfigurationProvider(file,  false , servletContext));
                }
            } 
else  {
                
throw   new  IllegalArgumentException( " Invalid configuration file name " );
            }
        }
    }
    对于其它配置文件只用StrutsXmlConfigurationProvider,此类继承XmlConfigurationProvider,而XmlConfigurationProvider又实现ConfigurationProvider接口。类XmlConfigurationProvider负责配置文件的读取和解析,addAction()方法负责读取<action>标签,并将数据保存在ActionConfig中;addResultTypes()方法负责将<result-type>标签转化为ResultTypeConfig对象;loadInterceptors()方法负责将<interceptor>标签转化为InterceptorConfi对象;loadInterceptorStack()方法负责将<interceptor-ref>标签转化为InterceptorStackConfig对象;loadInterceptorStacks()方法负责将<interceptor-stack>标签转化成InterceptorStackConfig对象。而上面的方法最终会被addPackage()方法调用,将所读取到的数据汇集到PackageConfig对象中。来看XmlConfigurationProvider的源代码,详细的我自己也就大体浏览了一下,各位可以自己研读。
     protected  PackageConfig addPackage(Element packageElement)  throws  ConfigurationException {
        PackageConfig.Builder newPackage 
=  buildPackageContext(packageElement);

        
if  (newPackage.isNeedsRefresh()) {
            
return  newPackage.build();
        }
        .

        addResultTypes(newPackage, packageElement);
        loadInterceptors(newPackage, packageElement);
        loadDefaultInterceptorRef(newPackage, packageElement);
        loadDefaultClassRef(newPackage, packageElement);
        loadGlobalResults(newPackage, packageElement);
        loadGobalExceptionMappings(newPackage, packageElement);
        NodeList actionList 
=  packageElement.getElementsByTagName( " action " );

        
for  ( int  i  =   0 ; i  <  actionList.getLength(); i ++ ) {
            Element actionElement 
=  (Element) actionList.item(i);
            addAction(actionElement, newPackage);
        }
        loadDefaultActionRef(newPackage, packageElement);
        PackageConfig cfg 
=  newPackage.build();
        configuration.addPackageConfig(cfg.getName(), cfg);
        
return  cfg;
    }
    这儿发现一个配置上的小技巧,我的xwork2.0.*是没有的,但是看源码是看到xwork2.1.*是可以的。继续看XmlConfigurationProvider的源代码:
     private  List loadConfigurationFiles(String fileName, Element includeElement) {
        List
< Document >  docs  =   new  ArrayList < Document > ();
        
if  ( ! includedFileNames.contains(fileName)) {
                
                Element rootElement 
=  doc.getDocumentElement();
                NodeList children 
=  rootElement.getChildNodes();
                
int  childSize  =  children.getLength();

                
for  ( int  i  =   0 ; i  <  childSize; i ++ ) {
                    Node childNode 
=  children.item(i);

                    
if  (childNode  instanceof  Element) {
                        Element child 
=  (Element) childNode;

                        
final  String nodeName  =  child.getNodeName();
                        
// 解析每个action配置是,对于include文件可以使用通配符*来进行配置
                        
// 如Struts.xml中可配置成<include file="actions_*.xml"/>
                         if  (nodeName.equals( " include " )) {
                            String includeFileName 
=  child.getAttribute( " file " );
                            
if (includeFileName.indexOf( ' * ' )  !=   - 1  ) {
                                ClassPathFinder wildcardFinder 
=   new  ClassPathFinder();
                                wildcardFinder.setPattern(includeFileName);
                                Vector
< String >  wildcardMatches  =  wildcardFinder.findMatches();
                                
for  (String match : wildcardMatches) {
                                    docs.addAll(loadConfigurationFiles(match, child));
                                }
                            }
                            
else  {
                                
                                docs.addAll(loadConfigurationFiles(includeFileName, child));    
                            }    
                    }
                }
                }
                docs.add(doc);
                loadedFileUrls.add(url.toString());
            }
        }
        
return  docs;
    }
    init_CustomConfigurationProviders方式初始自定义的Provider,配置类全名和实现ConfigurationProvider接口,用逗号隔开即可。
     private   void  init_CustomConfigurationProviders() {
        String configProvs 
=  initParams.get( " configProviders " );
        
if  (configProvs  !=   null ) {
            String[] classes 
=  configProvs.split( " \\s*[,]\\s* " );
            
for  (String cname : classes) {
                
try  {
                    Class cls 
=  ClassLoaderUtils.loadClass(cname,  this .getClass());
                    ConfigurationProvider prov 
=  (ConfigurationProvider)cls.newInstance();
                    configurationManager.addConfigurationProvider(prov);
                }
                
            }
        }
    }
    好了,现在再回到FilterDispatcher,每次发送一个Request,FilterDispatcher都会调用doFilter方法。
     public   void  doFilter(ServletRequest req, ServletResponse res, FilterChain chain)  throws  IOException, ServletException {

        HttpServletRequest request 
=  (HttpServletRequest) req;
        HttpServletResponse response 
=  (HttpServletResponse) res;
        ServletContext servletContext 
=  getServletContext();

        String timerKey 
=   " FilterDispatcher_doFilter:  " ;
        
try  {
            ValueStack stack 
=  dispatcher.getContainer().getInstance(ValueStackFactory. class ).createValueStack();
            ActionContext ctx 
=   new  ActionContext(stack.getContext());
            ActionContext.setContext(ctx);
            
            UtilTimerStack.push(timerKey);
            
// 根据content type来使用不同的Request封装,可以参见Dispatcher的wrapRequest
            request  =  prepareDispatcherAndWrapRequest(request, response);
            ActionMapping mapping;
            
try  {
                
// 根据url取得对应的Action的配置信息--ActionMapping,actionMapper是通过Container的inject注入的
                mapping  =  actionMapper.getMapping(request, dispatcher.getConfigurationManager());
            } 
catch  (Exception ex) {
                log.error(
" error getting ActionMapping " , ex);
                dispatcher.sendError(request, response, servletContext, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);
                
return ;
            }
            
// 如果找不到对应的action配置,则直接返回。比如你输入***.jsp等等
            
// 这儿有个例外,就是如果path是以“/struts”开头,则到初始参数packages配置的包路径去查找对应的静态资源并输出到页面流中,当然.class文件除外。如果再没有则跳转到404
             if  (mapping  ==   null ) {
                
//  there is no action in this request, should we look for a static resource?
                String resourcePath  =  RequestUtils.getServletPath(request);

                
if  ( "" .equals(resourcePath)  &&   null   !=  request.getPathInfo()) {
                    resourcePath 
=  request.getPathInfo();
                }

                
if  (serveStatic  &&  resourcePath.startsWith( " /struts " )) {
                    String name 
=  resourcePath.substring( " /struts " .length());
                    findStaticResource(name, request, response);
                } 
else  {
                    chain.doFilter(request, response);
                }
                
return ;
            }
            
// 正式开始Action的方法了
            dispatcher.serviceAction(request, response, servletContext, mapping);

        } 
finally  {
            
try  {
                ActionContextCleanUp.cleanUp(req);
            } 
finally  {
                UtilTimerStack.pop(timerKey);
            }
        }
    }
    Dispatcher类的serviceAction方法:
     public   void  serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,ActionMapping mapping)  throws  ServletException {

        Map
< String, Object >  extraContext  =  createContextMap(request, response, mapping, context);

        
//  If there was a previous value stack, then create a new copy and pass it in to be used by the new Action
        ValueStack stack  =  (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
        
if  (stack  !=   null ) {
            extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack));
        }

        String timerKey 
=   " Handling request from Dispatcher " ;
        
try  {
            UtilTimerStack.push(timerKey);
            String namespace 
=  mapping.getNamespace();
            String name 
=  mapping.getName();
            String method 
=  mapping.getMethod();

            Configuration config 
=  configurationManager.getConfiguration();
            ActionProxy proxy 
=  config.getContainer().getInstance(ActionProxyFactory. class ).createActionProxy(
                    namespace, name, method, extraContext, 
true ,  false );

            request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack());

            
//  if the ActionMapping says to go straight to a result, do it!
             if  (mapping.getResult()  !=   null ) {
                Result result 
=  mapping.getResult();
                result.execute(proxy.getInvocation());
            } 
else  {
                proxy.execute();
            }

            
//  If there was a previous value stack then set it back onto the request
             if  (stack  !=   null ) {
                request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);
            }
        } 
catch  (ConfigurationException e) {
            LOG.error(
" Could not find action or result " , e);
            sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e);
        } 
catch  (Exception e) {
            sendError(request, response, context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
        } 
finally  {
            UtilTimerStack.pop(timerKey);
        }
    }
    第一句createContextMap()方法,该方法主要把Application、Session、Request的key value值拷贝到Map中,并放在HashMap<String,Object>中,可以参见createContextMap方法:
     public  Map < String,Object >  createContextMap(HttpServletRequest request, HttpServletResponse response,
            ActionMapping mapping, ServletContext context) {

        
//  request map wrapping the http request objects
        Map requestMap  =   new  RequestMap(request);
        
//  parameters map wrapping the http parameters.  ActionMapping parameters are now handled and applied separately
        Map params  =   new  HashMap(request.getParameterMap());
        
//  session map wrapping the http session
        Map session  =   new  SessionMap(request);
        
//  application map wrapping the ServletContext
        Map application  =   new  ApplicationMap(context);
        Map
< String,Object >  extraContext  =  createContextMap(requestMap, params, session, application, request, response, context);
        extraContext.put(ServletActionContext.ACTION_MAPPING, mapping);
        
return  extraContext;
    }
    后面才是最主要的--ActionProxy,ActionInvocation。ActionProxy是Action的一个代理类,也就是说Action的调用是通过ActionProxy实现的,其实就是调用了ActionProxy.execute()方法,而该方法又调用了ActionInvocation.invoke()方法。归根到底,最后调用的是DefaultActionInvocation.invokeAction()方法。先看DefaultActionInvocation的init方法。
     public   void  init(ActionProxy proxy) {
        
this .proxy  =  proxy;
        Map contextMap 
=  createContextMap();

        
//  Setting this so that other classes, like object factories, can use the ActionProxy and other
        
//  contextual information to operate
        ActionContext actionContext  =  ActionContext.getContext();

        
if (actionContext  !=   null ) {
            actionContext.setActionInvocation(
this );
        }
        
// 创建Action,可Struts2里是每次请求都新建一个Action
        createAction(contextMap);

        
if  (pushAction) {
            stack.push(action);
            contextMap.put(
" action " , action);
        }

        invocationContext 
=   new  ActionContext(contextMap);
        invocationContext.setName(proxy.getActionName());

        
//  get a new List so we don't get problems with the iterator if someone changes the list
        List interceptorList  =   new  ArrayList(proxy.getConfig().getInterceptors());
        interceptors 
=  interceptorList.iterator();
    }

    
protected   void  createAction(Map contextMap) {
        
//  load action
        String timerKey  =   " actionCreate:  " + proxy.getActionName();
        
try  {
            UtilTimerStack.push(timerKey);
            
// 这儿默认建立Action是StrutsObjectFactory,实际中我使用的时候都是使用Spring创建的Action,这个时候使用的是SpringObjectFactory
            action  =  objectFactory.buildAction(proxy.getActionName(), proxy.getNamespace(), proxy.getConfig(), contextMap);
        } 
        ..
        } 
finally  {
            UtilTimerStack.pop(timerKey);
        }

        
if  (actionEventListener  !=   null ) {
            action 
=  actionEventListener.prepare(action, stack);
        }
    }
    接下来看看DefaultActionInvocation 的invoke方法。
    public  String invoke()  throws  Exception {
        String profileKey 
=   " invoke:  " ;
        
try  {
            UtilTimerStack.push(profileKey);
            
            
if  (executed) {
                
throw   new  IllegalStateException( " Action has already executed " );
            }
                
// 先执行interceptors
             if  (interceptors.hasNext()) {
                
final  InterceptorMapping interceptor  =  (InterceptorMapping) interceptors.next();
                UtilTimerStack.profile(
" interceptor:  " + interceptor.getName(), 
                        
new  UtilTimerStack.ProfilingBlock < String > () {
                            
public  String doProfiling()  throws  Exception {
                                resultCode 
=  interceptor.getInterceptor().intercept(DefaultActionInvocation. this );
                                
return   null ;
                            }
                });
            } 
else  {
                        
// interceptor执行完了之后执行action
                resultCode  =  invokeActionOnly();
            }

            
//  this is needed because the result will be executed, then control will return to the Interceptor, which will
            
//  return above and flow through again
             if  ( ! executed) {
                        
// 在Result返回之前调用preResultListeners
                 if  (preResultListeners  !=   null ) {
                    
for  (Iterator iterator  =  preResultListeners.iterator();
                        iterator.hasNext();) {
                        PreResultListener listener 
=  (PreResultListener) iterator.next();
                        
                        String _profileKey
= " preResultListener:  " ;
                        
try  {
                            UtilTimerStack.push(_profileKey);
                            listener.beforeResult(
this , resultCode);
                        }
                        
finally  {
                            UtilTimerStack.pop(_profileKey);
                        }
                    }
                }

                
//  now execute the result, if we're supposed to
                 if  (proxy.getExecuteResult()) {
                    executeResult();
                }

                executed 
=   true ;
            }

            
return  resultCode;
        }
        
finally  {
            UtilTimerStack.pop(profileKey);
        }
    }
    看程序中的if(interceptors.hasNext())语句,当然,interceptors里存储的是interceptorMapping列表(它包括一个Interceptor和一个name),所有的截拦器必须实现Interceptor的intercept方法,而该方法的参数恰恰又是ActionInvocation,在intercept方法中还是调用invocation.invoke(),从而实现了一个Interceptor链的调用。当所有的Interceptor执行完,最后调用invokeActionOnly方法来执行Action相应的方法。
     protected  String invokeAction(Object action, ActionConfig actionConfig)  throws  Exception {
        String methodName 
=  proxy.getMethod();
        String timerKey 
=   " invokeAction:  " + proxy.getActionName();
        
try  {
            UtilTimerStack.push(timerKey);
            
            
boolean  methodCalled  =   false ;
            Object methodResult 
=   null ;
            Method method 
=   null ;
            
try  {
                
// 获得需要执行的方法
                method  =  getAction().getClass().getMethod(methodName,  new  Class[ 0 ]);
            } 
catch  (NoSuchMethodException e) {
                
// 如果没有对应的方法,则使用do+Xxxx来再次获得方法
                 try  {
                    String altMethodName 
=   " do "   +  methodName.substring( 0 ,  1 ).toUpperCase()  +  methodName.substring( 1 );
                    method 
=  getAction().getClass().getMethod(altMethodName,  new  Class[ 0 ]);
                } 
catch  (NoSuchMethodException e1) {
                    
//  well, give the unknown handler a shot
                     if  (unknownHandler  !=   null ) {
                        
try  {
                            methodResult 
=  unknownHandler.handleUnknownActionMethod(action, methodName);
                            methodCalled 
=   true ;
                        } 
catch  (NoSuchMethodException e2) {
                            
//  throw the original one
                             throw  e;
                        }
                    } 
else  {
                        
throw  e;
                    }
                }
            }
            
            
if  ( ! methodCalled) {
                methodResult 
=  method.invoke(action,  new  Object[ 0 ]);
            }
            
// 根据不同的Result类型返回不同值
            
// 如输出流Result
             if  (methodResult  instanceof  Result) {
                
this .explicitResult  =  (Result) methodResult;
                
return   null ;
            } 
else  {
                
return  (String) methodResult;
            }
        } 
catch  (NoSuchMethodException e) {
            
throw   new  IllegalArgumentException( " The  "   +  methodName  +   " () is not defined in action  "   +  getAction().getClass()  +   "" );
        } 
catch  (InvocationTargetException e) {
            
//  We try to return the source exception.
            Throwable t  =  e.getTargetException();

            
if  (actionEventListener  !=   null ) {
                String result 
=  actionEventListener.handleException(t, getStack());
                
if  (result  !=   null ) {
                    
return  result;
                }
            }
            
if  (t  instanceof  Exception) {
                
throw (Exception) t;
            } 
else  {
                
throw  e;
            }
        } 
finally  {
            UtilTimerStack.pop(timerKey);
        }
    }
    好了,action执行完了,还要根据ResultConfig返回到view,也就是在invoke方法中调用executeResult方法。
     private   void  executeResult()  throws  Exception {
        
// 根据ResultConfig创建Result
        result  =  createResult();
        String timerKey 
=   " executeResult:  " + getResultCode();
        
try  {
            UtilTimerStack.push(timerKey);
            
if  (result  !=   null ) {
                
// 这儿正式执行:)
                
// 可以参考Result的实现,如用了比较多的ServletDispatcherResult,ServletActionRedirectResult,ServletRedirectResult
                result.execute( this );
            } 
else   if  (resultCode  !=   null   &&   ! Action.NONE.equals(resultCode)) {
                
throw   new  ConfigurationException( " No result defined for action  "   +  getAction().getClass().getName() 
                        
+   "  and result  "   +  getResultCode(), proxy.getConfig());
            } 
else  {
                
if  (LOG.isDebugEnabled()) {
                    LOG.debug(
" No result returned for action  " + getAction().getClass().getName() + "  at  " + proxy.getConfig().getLocation());
                }
            }
        } 
finally  {
            UtilTimerStack.pop(timerKey);
        }
    }
    
public  Result createResult()  throws  Exception {
        
if  (explicitResult  !=   null ) {
            Result ret 
=  explicitResult;
            explicitResult 
=   null ;;
            
return  ret;
        }
        ActionConfig config 
=  proxy.getConfig();
        Map results 
=  config.getResults();
        ResultConfig resultConfig 
=   null ;
        
synchronized  (config) {
            
try  {
                
// 根据result名称获得ResultConfig,resultCode就是result的name
                resultConfig  =  (ResultConfig) results.get(resultCode);
            } 
catch  (NullPointerException e) {
            }
            
if  (resultConfig  ==   null ) {
                
// 如果找不到对应name的ResultConfig,则使用name为*的Result
                resultConfig  =  (ResultConfig) results.get( " * " );
            }
        }
        
if  (resultConfig  !=   null ) {
            
try  {
                
// 参照StrutsObjectFactory的代码
                Result result  =  objectFactory.buildResult(resultConfig, invocationContext.getContextMap());
                
return  result;
            } 
catch  (Exception e) {
                LOG.error(
" There was an exception while instantiating the result of type  "   +  resultConfig.getClassName(), e);
                
throw   new  XWorkException(e, resultConfig);
            }
        } 
else   if  (resultCode  !=   null   &&   ! Action.NONE.equals(resultCode)  &&  unknownHandler  !=   null ) {
            
return  unknownHandler.handleUnknownResult(invocationContext, proxy.getActionName(), proxy.getConfig(), resultCode);
        }
        
return   null ;
    }
    
// StrutsObjectFactory
     public  Result buildResult(ResultConfig resultConfig, Map extraContext)  throws  Exception {
        String resultClassName 
=  resultConfig.getClassName();
        
if  (resultClassName  ==   null )
            
return   null ;
        
// 创建Result,因为Result是有状态的,所以每次请求都新建一个
        Object result  =  buildBean(resultClassName, extraContext);
        
// 这句很重要,后面将会谈到,reflectionProvider参见OgnlReflectionProvider;
        
// resultConfig.getParams()就是result配置文件里所配置的参数<param></param>
        
// setProperties方法最终调用的是Ognl类的setValue方法
        
// 这句其实就是把param名值设置到根对象result上
        reflectionProvider.setProperties(resultConfig.getParams(), result, extraContext);
        
if  (result  instanceof  Result)
            
return  (Result) result;
        
throw   new  ConfigurationException(result.getClass().getName()  +   "  does not implement Result. " );
    }
    最后补充一下,Struts2的查找值和设置值都是使用Ognl来实现的。关于Ognl的介绍可以到其官方网站查看http://www.ognl.org/,我在网上也找到另外一篇http://www.javaeye.com/topic/254684和http://www.javaeye.com/topic/223612。完了来看下面这段小测试程序(其它的Ognl的测试可以自己添加)。
public   class  TestOgnl {
    
    
private  User user;
    
private  Map context;
    
    @Before
    
public   void  setUp()  throws  Exception {
    
    }

    @Test
    
public   void  ognlGetValue()  throws  Exception {
    reset();
    Assert.assertEquals(
" myyate " , Ognl.getValue( " name " , user));
    Assert.assertEquals(
" cares " , Ognl.getValue( " dept.name " , user));
    Assert.assertEquals(
" myyate " , Ognl.getValue( " name " , context, user));
    Assert.assertEquals(
" contextmap " , Ognl.getValue( " #name " , context, user));
    Assert.assertEquals(
" parker " , Ognl.getValue( " #pen " , context, user));
    }
    
    @Test
    
public   void  ognlSetValue()  throws  Exception {
    reset();
    Ognl.setValue(
" name " , user,  " myyateC " );
    Assert.assertEquals(
" myyateC " , Ognl.getValue( " name " , user));
    
    Ognl.setValue(
" dept.name " , user,  " caresC " );
    Assert.assertEquals(
" caresC " , Ognl.getValue( " dept.name " , user));
    
    Assert.assertEquals(
" contextmap " , Ognl.getValue( " #name " , context, user));
    Ognl.setValue(
" #name " , context, user,  " contextmapC " );
    Assert.assertEquals(
" contextmapC " , Ognl.getValue( " #name " , context, user));
    
    Assert.assertEquals(
" parker " , Ognl.getValue( " #pen " , context, user));
    Ognl.setValue(
" #name " , context, user,  " parkerC " );
    Assert.assertEquals(
" parkerC " , Ognl.getValue( " #name " , context, user));
    }
    
    
public   static   void  main(String[] args)  throws  Exception {
    JUnitCore.runClasses(TestOgnl.
class );
    }
    
    
private   void  reset() {
    user 
=   new  User( " myyate " ,  new  Dept( " cares " ));
    context 
=   new  OgnlContext();
    context.put(
" pen " ,  " parker " );
    context.put(
" name " ,  " contextmap " );
    }
}

class  User {
    
public  User(String name, Dept dept) {
    
this .name  =  name;
    
this .dept  =  dept;
    }
    String name;
    
private  Dept dept;
    
public  Dept getDept() {
        
return  dept;
    }
    
public  String getName() {
        
return  name;
    }
    
public   void  setDept(Dept dept) {
        
this .dept  =  dept;
    }
    
public   void  setName(String name) {
        
this .name  =  name;
    }
}

class  Dept {
    
public  Dept(String name) {
    
this .name  =  name;
    }
    
private  String name;
    
public  String getName() {
        
return  name;
    }
    
public   void  setName(String name) {
        
this .name  =  name;
    }
}
    这样,一个Struts2的请求流程基本上就结束了。其实我觉得做项目把Struts2参考文档看两遍就可以了,呵呵!(写博客比看代码还累)

转载出处:http://www.blogjava.net/myyate/articles/Struts2_source_java.html




深入Struts2框架:源码解读与实践指南 本文还有配套的精品资源,点击获取 简介:Struts2是一个基于MVC模式的Java Web框架,本课程通过分析Struts2项目的关键文件和目录结构,帮助学习者理解其工作原理和开发细节。课程内容涉及 .classpath 、 .mymetadata 、 .project 、 .settings 和 .myec... 阅读详情

相关推荐

深入分析Struts2程序源码

本文还有配套的精品资源,点击获取 简介:Struts2是一个基于MVC设计模式的开源Java Web框架,由Apache软件基金会维护。它继承并改进了Struts1,提供了强大的功能和灵活性,以构建高效且易于维护的Web应用。本文深入剖析Struts2的核心架构、配置机制、ActionMapping、ValueStack、Tiles集成、国际化支持、异常处理、安全防护以及与...

weixin_28933797的博客 1031

Struts2源码分析

Struts2架构图        请求首先通过Filter chain,Filter主要包括ActionContextCleanUp,它主要清理当前线程的ActionContext和Dispatcher;FilterDispatcher主要通过AcionMapper来决定需要调用哪个Action。        ActionMapper取得了ActionMapping后,在Dispa

lick4050312的专栏 3649

在树莓派5(8G版)上运行Ollama + LLM

直接上结论,Ollama在树莓派上能安装,且本身运行起来毫无压力,但具体到大语言模型,Deepseek似乎不总是最佳选择。

ki1381的专栏 1661

struts2的ActionContext源代码解析

ActionContext.getContext().put("name","liming");和Map request = (Map)ActionContext.getContext().get("request");request.put("name","liming");设置name变量,当需要在jsp中显示时,可以通过OGNL读取。 ActionContext(com.opensymph

john2522的专栏 6538

2025虚幻游戏逆向工程解包尝试

2025虚幻游戏逆向工程解包指南 本文详细介绍了虚幻引擎5游戏逆向解包的完整流程,主要包括获取AES密钥、生成映射文件和导出资源三个关键步骤。作者在实际操作中遇到诸多难题:AES密钥获取工具存在加壳保护问题,映射文件生成器依赖复杂的VS编译环境,DLL注入工具的使用也存在技术门槛。通过多次尝试,作者发现部分游戏可直接搜索现成的AES密钥,而映射文件生成需要额外下载Memcury依赖库才能正常编译。文章提供了相关工具的下载链接和具体操作说明,但同时也指出每个环节都可能出现意外状况,逆向工程实际执行过程远比理论

wsdchong的博客 6189

Mediapipe入门——搭建姿态检测模型并实时输出人体关节点3d坐标(2024.1.4更新)

Mediapipe入门,利用mediapipe搭建人体整体检测模型,并输出右手21个关节点的坐标;mp_holistic.Holistic函数理解,mp_holistic.Holistic.process函数理解;mp.solutions.drawing_utils.draw_landmarks函数理解;Mediapipe实时姿态估计,3d骨架铰接图,matplotlib和Mediapipe绘图

kalakalabala的博客 6万+

代码清单12:DefaultActionMapper.getMapping()方法

public ActionMapping getMapping(HttpServletRequest request, ConfigurationManager configManager) { ActionMapping mapping = new ActionMapping(); String uri = getUri(request);//得到请求路径的URI,如:testAction

evilcry2012的专栏 598

嵌入式充电协议深度解析:从QC到PD3.1的技术演进与实战应用

本文深入解析了从QC到PD3.1的嵌入式充电协议技术演进与实战应用。通过电压谈判、协议芯片设计、Type-C接口优化等关键技术,详细介绍了快充协议在嵌入式系统中的实现挑战与解决方案,包括兼容性测试、EMC问题处理及空间限制创新设计,为开发者提供了宝贵的实践经验。

weixin_29194817的博客 426

Struts2的工作机制及分析(转)

Struts2的工作机制及分析(转) 概述   本章讲述Struts2的工作原理。   读者如果曾经学习过Struts1.x或者有过Struts1.x的开发经验,那么千万不要想当然地以为这一章可以跳过。实际上Struts1.x与Struts2并无我们想象的血缘关系。虽然Struts2的开发小组极力保留Struts1.x的习惯,但因为Struts2的核心设计完全改变,从思想到设计到工作流程,都

liuvlun的专栏 705

【人工智能之深度学习】18. 金融风控实战:TCN时序卷积网络构建信用卡欺诈实时检测系统

摘要:信用卡欺诈交易识别是金融风控的核心环节,其面临欺诈样本占比低(仅0.1%)、实时响应要求高(毫秒级)等挑战。本文基于IEEE-CIS公开数据集,构建基于时序卷积网络(TCN)的欺诈检测系统,通过捕捉用户交易行为的时序模式识别异常。详细阐述全流程:从数据预处理(构造交易序列特征)、TCN模型设计(轻量级架构适配实时场景),到实时检测部署(异步处理确保低延迟)。实验显示,该系统精确率达63%、召回率89%,误杀率仅0.2%,推理延迟8ms,较XGBoost等传统模型性能显著提升。

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 1144

【CANoe示例分析】SOMEIPWithvCDL_16

本示例来源于官方提供的示例工程:0004_基于vCDL实现SOMEIP通信_Demo\0004_基于vCDL实现SOMEIP通信_Demo\SOMEIPWithvCDL。

jasonj333 578

Struts2==>default.properties

###Project_name ==> Java Resources ==> Libraries ==> Web App Libraries ###                         ==> struts2-core-2.5.5.jar  ==> org.apache.struts2 ###                        ==> static ==> defaul

lzhat的博客 604

Autosar诊断实战系列05-Dcm之0x27加解密服务配置开发详解

UDS 0x27服务实战开发介绍,对解锁尝试次数及delay时间进一步解释。

initiallizer的博客 2000

Struts2体系结构图以及详解

Strut2的体系结构如图所示: 一个请求在Struts2框架中的处理大概分为以下几个步骤: 1、客户端初始化一个指向Servlet容器(例如Tomcat)的请求;2、这个请求经过一系列的过滤器(Filter)(这些过滤器中有一个叫做ActionContextCleanUp的可选过滤器,这个过滤器对于Struts2和其他框架的集成很有帮助,例如:SiteMesh Plugin);3、接着Filt

郭東的博客 2224

【YOLO系列】YOLOv8详解:模型结构、损失函数、训练方法及代码实现

YOLOv8是Ultralytics团队2023年推出的高效目标检测框架,在速度与精度平衡、多任务支持和易用性方面实现突破。模型采用改进的CSPDarknet主干网络、C2f模块和SPPF加速结构,结合PAN-FPN特征融合和解耦检测头设计,支持目标检测、实例分割和关键点检测任务。创新性地使用CIoU定位损失、Focal Loss置信度损失和动态样本分配策略,显著提升检测性能。实验表明,YOLOv8较前代模型mAP提升5-10%,在TensorRT加速下可达1000FPS,提供5种尺寸灵活选择,成为实时目标

一碗白开水一 2787

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

struts2拦截器的实现原理及源码剖析

本文来自:http://blog.csdn.net/csh624366188 拦截器(interceptor)是Struts2最强大的特性之一,也可以说是struts2的核心,拦截器可以让你在Action和result被执行之前或之后进行一些处理。同时,拦截器也可以让你将通用的代码模块化并作为可重用的类。Struts2中的很多特性都是由拦截器来完成的。拦截是AOP的一种实现策略。在Web

不积跬步无以至千里,不积小流无以成江海 684

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

struts2中如何根据请求路径定位到详细的访问action

struts2中如何根据请求路径定位到详细的访问action 在struts2中在访问一个菜单链接时,我们只需要将相应的package命名空间和action的name进行组合,并加上相应的后缀,就可以直接访问到相应的Action了,那么这个过程是如何进行的,多个相同命名空间的package是如何满足互不冲突的呢,这就需要详细了解strut...

weixin_30535565的博客 524

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Probability and Statistics - 4th edition

Probability and Statistics - 4th edition

struts2源代码分析

1. Struts2架构图 请求首先通过Filter chain,Filter主要包括ActionContextCleanUp,它主要清理当前线程的ActionContext和Dispatcher;FilterDispatcher主要通过AcionMapper来决定需要调用哪个Action。         ActionMapper取得了ActionMapping后,在Dispatcher

mq1097762241的专栏 756

Struts2框架原理

Struts2官网 https://struts.apache.org/ Struts2是一个开源的轻量级的,应用于web层(View)的框架。 Struts2框架的MVC分别对应: M:JavaBean + ModelDriven V:JSP + OGNL C:Action Struts2框架的控制器将“获取请求”和“分发转向”代码抽取出来写在配置文件中,这样一样,控制器(a...

云下的你 5852

struts2的actionMapper是做什么的?

源码如下, package org.apache.struts2.dispatcher.mapper; import com.opensymphony.xwork2.config.ConfigurationManager; import javax.servlet.http.HttpServletRequest; public interface ActionMapper { Act...

深海微澜 1668

ActionMapper 是干什么用的?

public abstract interface org.apache.struts2.dispatcher.mapper.ActionMapper {} public abstract org.apache.struts2.dispatcher.mapper.ActionMapping getMapping(javax.servlet.http.HttpServletRequest arg0,

winder9898的博客 5207

Apache Struts2再爆高危漏洞

60网站安全检测最新struts2命令执行漏洞分析 时间:2013-07-18 09:46   在struts2中,DefaultActionMapper类支持以"action:"、"redirect:"、"redirectAction:"作为导航或是重定向前缀,但是这些前缀后面同时可以跟OGNL表达式,由于struts2没有对这些前缀做过滤,

dongdong_java的专栏 8382

Struts2架构图

Struts2架构图          请求首先通过Filter chain,Filter主要包括ActionContextCleanUp,它主要清理当前线程的ActionContext和Dispatcher;FilterDispatcher主要通过AcionMapper来决定需要调用哪个Action。          ActionMapper取得了ActionMapping后,在D

Jston的专栏 1719

struts2架构图

目录    struts2访问流程图分析    struts2架构图分析    struts2.xml配置    struts2常量配置    struts2配置进阶:动态方法调用 struts2访问流程图分析:  struts2架构图分析     strutsPrepareAndExecuteFilter 相当于前台 actionMap 相当于服务员,比如你要访问那个...

u012222212的专栏 328

strurts2 中的 ActionMapper的 作用

最近在项目中要做http api,要求提供的url是 http://***.domain.com/api/rest?sign={签名}&method={namespace}.{action名}.{调用方法名}&......   类似淘宝的top api url 风格,一个url,根据参数不同,映射到不同的控制器。   实现方法详细:   1、实现自己的Actio

zesus的博客 1157
上一篇: 怎么从ActionInvocation(拦截器)中获取用户jsp表单提交的所有值,比如用户输入的任意项
下一篇: 李刚java疯狂讲义(笔记)
kinmin2012
博客等级 码龄14年 10粉丝 28原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值