小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

Struts2 處理流程詳細(xì)分析

 CevenCheng 2010-09-27

1. 當(dāng)Servlet容器接收到一個(gè)請求后,將請求交給你在wed.xml文件中配置的過濾器FilterDispatcher。 
FilterDispatcher類的處理流程: 
1.1 FilterDispatcher類實(shí)現(xiàn)了StrutsStatics, Filter這二個(gè)接口。StrutsStatics類定義了Struts2的常量。在這里不詳細(xì)介紹了。主要介紹Filter接口類,它核心有三個(gè)主要方法,doFilter、init和destroy。 
1.1.1 init方法的使用 
首先創(chuàng)建一個(gè)FilterConfig類 
通過該查詢是否已經(jīng)存在一個(gè)日志文件,如果不存在則創(chuàng)建一個(gè)日志文件。(2.0沒) 
 private void initLogging() { 
         String factoryName = filterConfig.getInitParameter("loggerFactory"); 
         if (factoryName != null) { 
             try { 
                 Class cls = ClassLoaderUtils.loadClass(factoryName, this.getClass()); 
                 LoggerFactory fac = (LoggerFactory) cls.newInstance(); 
                 LoggerFactory.setLoggerFactory(fac); 
             } catch (InstantiationException e) { 
      System.err.println("Unable to instantiate logger factory: " + factoryName + ", using default"); 
                 e.printStackTrace(); 
             } catch (IllegalAccessException e) { 
      System.err.println("Unable to access logger factory: " + factoryName + ", using default"); 
                 e.printStackTrace(); 
             } catch (ClassNotFoundException e) { 
      System.err.println("Unable to locate logger factory class: " + factoryName + ", using default"); 
                 e.printStackTrace(); 
             } 
         } 
         log = LoggerFactory.getLogger(FilterDispatcher.class); 
 } 
接著調(diào)用Dispatcher createDispatcher()方法,獲取wed.xml文件中的配置信息,并通過一個(gè)MAP對象進(jìn)行存儲。 
 protected Dispatcher createDispatcher(FilterConfig filterConfig) { 
         Map<String, String> params = new HashMap<String, String>(); 
         for (Enumeration e = filterConfig.getInitParameterNames(); e.hasMoreElements();) { 
             String name = (String) e.nextElement(); 
             String value = filterConfig.getInitParameter(name); 
             params.put(name, value); 
         } 
         return new Dispatcher(filterConfig.getServletContext(), params); 
 } 
對象例子

<init-param> 
   <param-name>encoding</param-name> 
   <param-value>gb2312</param-value> 
</init-param> 
接著把獲取到的相關(guān)參數(shù)傳給Dispatcher類。這個(gè)類主要實(shí)現(xiàn)對配置文件信息的獲取,根據(jù)配置信息,讓不同的action的結(jié)果返回到不同的頁面。 
進(jìn)入到Dispatcher類,首先調(diào)用其init()方法,獲取配置信息。 
○1首先實(shí)例化一個(gè)ConfigurationManager對象。 
○2接著調(diào)用init_DefaultProperties()方法,這個(gè)方法中是將一個(gè)DefaultPropertiesProvider對象追加到ConfigurationManager對象內(nèi)部的ConfigurationProvider隊(duì)列中。 DefaultPropertiesProvider的register()方法可以載入org/apache/struts2/default.properties中定義的屬性。 
 DefaultPropertiesProvider類中的register()方法 
 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); 
 }

 ConfigurationManager類中的addConfigurationProvider()方法 
 public void addConfigurationProvider(ConfigurationProvider provider) { 
         if (!configurationProviders.contains(provider)) { 
             configurationProviders.add(provider); 
         } 
 }

 init_DefaultProperties()方法 
 private void init_DefaultProperties() { 
         configurationManager.addConfigurationProvider(new DefaultPropertiesProvider()); 
 }

○3接著調(diào)用init_TraditionalXmlConfigurations()方法,實(shí)現(xiàn)載入FilterDispatcher的配置中所定義的config屬性。 如果用戶沒有定義config屬性,struts默認(rèn)會載入DEFAULT_CONFIGURATION_PATHS這個(gè)值所代表的xml文件。它的值為"struts-default.xml,struts-plugin.xml,struts.xml"。也就是說框架默認(rèn)會載入這三個(gè)項(xiàng)目xml文件。如果文件類型是XML格式,則按照xwork-x.x.dtd模板進(jìn)行讀取。如果,是Struts的配置文件,則按struts-2.X.dtd模板進(jìn)行讀取。


 private void init_TraditionalXmlConfigurations() { 
         String configPaths = initParams.get("config"); 
         if (configPaths == null) { 
             configPaths = DEFAULT_CONFIGURATION_PATHS; 
         } 
         String[] files = configPaths.split("\\s*[,]\\s*"); 
         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"); 
             } 
         } 
 }

 XmlConfigurationProvider類對文件讀取的模式 
 public void register(ContainerBuilder containerBuilder, LocatableProperties props) throws ConfigurationException {
  LOG.info("Parsing configuration file [" + configFileName + "]");
  Map<String, Node> loadedBeans = new HashMap<String, Node>();
  for (Document doc : documents) {
   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();
     if (nodeName.equals("bean")) {
      String type = child.getAttribute("type");
      String name = child.getAttribute("name");
      String impl = child.getAttribute("class");
      String onlyStatic = child.getAttribute("static");
      String scopeStr = child.getAttribute("scope");
      boolean optional = "true".equals(child.getAttribute("optional"));
      Scope scope = Scope.SINGLETON;
      if ("default".equals(scopeStr)) {
       scope = Scope.DEFAULT;
      } else if ("request".equals(scopeStr)) {
       scope = Scope.REQUEST;
      } else if ("session".equals(scopeStr)) {
       scope = Scope.SESSION;
      } else if ("singleton".equals(scopeStr)) {
       scope = Scope.SINGLETON;
      } else if ("thread".equals(scopeStr)) {
       scope = Scope.THREAD;
      }
      if (!TextUtils.stringSet(name)) {
       name = Container.DEFAULT_NAME;
      }
      try {
       Class cimpl = ClassLoaderUtil.loadClass(impl,
         getClass());
       Class ctype = cimpl;
       if (TextUtils.stringSet(type)) {
        ctype = ClassLoaderUtil.loadClass(type,
          getClass());
       }
       if ("true".equals(onlyStatic)) {
        // Force loading of class to detect no class def found exceptions 
        cimpl.getDeclaredClasses();
        containerBuilder.injectStatics(cimpl);
       } else {
        if (containerBuilder.contains(ctype, name)) {
         Location loc = LocationUtils
           .getLocation(loadedBeans.get(ctype
             .getName()
             + name));
         throw new ConfigurationException(
           "Bean type "
             + ctype
             + " with the name "
             + name
             + " has already been loaded by "
             + loc, child);
        }
        // Force loading of class to detect no class def found exceptions 
        cimpl.getDeclaredConstructors();
        if (LOG.isDebugEnabled()) {
         LOG.debug("Loaded type:" + type + " name:"
           + name + " impl:" + impl);
        }
        containerBuilder
          .factory(ctype, name,
            new LocatableFactory(name,
              ctype, cimpl, scope,
              childNode), scope);
       }
       loadedBeans.put(ctype.getName() + name, child);
      } catch (Throwable ex) {
       if (!optional) {
        throw new ConfigurationException(
          "Unable to load bean: type:" + type
            + " class:" + impl, ex,
          childNode);
       } else {
        LOG.debug("Unable to load optional class: "
          + ex);
       }
      }
     } else if (nodeName.equals("constant")) {
      String name = child.getAttribute("name");
      String value = child.getAttribute("value");
      props.setProperty(name, value, childNode);
     }
    }
   }
  }
 }

 StrutsXmlConfigurationProvider類繼承于它,獲取大至相同。獲取那些對象后,把它們追加到ConfigurationManager對象內(nèi)部的ConfigurationProvider隊(duì)列中。

○4 接著調(diào)用init_LegacyStrutsProperties()方法,創(chuàng)建一個(gè)LegacyPropertiesConfigurationProvider類,并將它追加到ConfigurationManager對象內(nèi)部的ConfigurationProvider隊(duì)列中。LegacyPropertiesConfigurationProvider類載入struts.properties中的配置,這個(gè)文件中的配置可以覆蓋default.properties中的。其子類是DefaultPropertiesProvider類。

 private void init_LegacyStrutsProperties() { 
         configurationManager.addConfigurationProvider( 
 new LegacyPropertiesConfigurationProvider()); 
 }

○5接著調(diào)用init_ZeroConfiguration()方法,這次處理的是FilterDispatcher的配置中所定義的actionPackages屬性。該參數(shù)的值是一個(gè)以英文逗號(,)隔開的字符串,每個(gè)字符串都是一個(gè)包空間,Struts 2框架將掃描這些包空間下的Action類。實(shí)現(xiàn)的是零配置文件信息獲取。它能夠能根據(jù)web.xml中配置的actionPackages自動掃描所有Action類,并猜測其NameSpace. 再利用CodeBehind猜測Result指向的jsp,實(shí)現(xiàn)了struts.xml的零配置(其實(shí)也不是完全沒有struts.xml,而是指struts.xml的內(nèi)容不會隨action的增加而膨脹)。 
如果有特殊的結(jié)果指向(如redirect類型的結(jié)果),在Action處用@Result配置。 
    如有package級的配置(如使用非默認(rèn)的Interceptor棧),仍在struts.xml中定義package,用@ParentPackage指定。 
    不過,目前ZeroConfig的Annotation較少,只有@Result、@ParentPackage,@NameSpace(java的package名不符合約定規(guī)則時(shí)使用),還有exception-Mapping之類的配置沒有包含。 
 private void init_ZeroConfiguration() { 
  String packages = initParams.get("actionPackages"); 
  if (packages != null) { 
      String[] names = packages.split("\\s*[,]\\s*"); 
      // Initialize the classloader scanner with the configured packages 
      if (names.length > 0) { 
          ClasspathConfigurationProvider provider = 
   new ClasspathConfigurationProvider(names); 
          provider.setPageLocator( 
   new ServletContextPageLocator(servletContext)); 
          configurationManager.addConfigurationProvider(provider); 
      } 
  } 
 }

○6接著調(diào)用init_CustomConfigurationProviders()方法,此方法處理的是FilterDispatcher的配置中所定義的configProviders屬性。負(fù)責(zé)載入用戶自定義的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); 
    } catch (InstantiationException e) { 
        throw new ConfigurationException("Unable to instantiate provider: "+cname, e); 
    } catch (IllegalAccessException e) { 
        throw new ConfigurationException("Unable to access provider: "+cname, e); 
    } catch (ClassNotFoundException e) { 
        throw new ConfigurationException("Unable to locate provider class: "+cname, e); 
    } 
   } 
  } 
 }

○7接著調(diào)用init_MethodConfigurationProvider()方法,但該方法已經(jīng)被注釋了。 
○8接著調(diào)用init_FilterInitParameters()方法,此方法用來處理FilterDispatcher的配置中所定義的所有屬性。

 private void init_FilterInitParameters() { 
         configurationManager.addConfigurationProvider(new ConfigurationProvider() { 
             public void destroy() {} 
             public void init(Configuration configuration) throws ConfigurationException {} 
             public void loadPackages() throws ConfigurationException {} 
             public boolean needsReload() { return false; } 
             public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException { 
                 props.putAll(initParams); 
             } 
         }); 
 }

○9接著調(diào)用init_AliasStandardObjects()方法,并將一個(gè)BeanSelectionProvider類追加到ConfigurationManager對象內(nèi)部的ConfigurationProvider隊(duì)列中。BeanSelectionProvider類主要實(shí)現(xiàn)加載org/apache/struts2/struts-messages。

 private void init_AliasStandardObjects() { 
         configurationManager.addConfigurationProvider(new BeanSelectionProvider()); 
 }

○10接著調(diào)用init_PreloadConfiguration()方法,構(gòu)建調(diào)用上邊幾步添加到ConfigurationManager的getConfiguration()獲取當(dāng)前XWork配置對象。

 private Container init_PreloadConfiguration() { 
         Configuration config = configurationManager.getConfiguration(); 
         Container container = config.getContainer();

         boolean reloadi18n = Boolean.valueOf(container.getInstance( 
  String.class, StrutsConstants.STRUTS_I18N_RELOAD)); 
         LocalizedTextUtil.setReloadBundles(reloadi18n); 
         ObjectTypeDeterminer objectTypeDeterminer = container.getInstance(ObjectTypeDeterminer.class); 
         ObjectTypeDeterminerFactory.setInstance(objectTypeDeterminer); 
         return container; 
 }


 configurationManager.getConfiguration()方法 
 public synchronized Configuration getConfiguration() { 
         if (configuration == null) { 
             setConfiguration(new DefaultConfiguration(defaultFrameworkBeanName)); 
             try { 
                 configuration.reload(getConfigurationProviders()); 
             } catch (ConfigurationException e) { 
                 setConfiguration(null); 
                 throw e; 
             } 
         } else { 
             conditionalReload(); 
         } 
         return configuration; 
 }

○11接著調(diào)用init_CheckConfigurationReloading(container)方法,檢查配置重新加載。(具體怎樣不清楚)

 private void init_CheckConfigurationReloading(Container container) { 
         FileManager.setReloadingConfigs("true".equals(container.getInstance( 
 String.class, StrutsConstants.STRUTS_CONFIGURATION_XML_RELOAD))); 
 }

○12接著調(diào)用init_CheckWebLogicWorkaround(Container container)方法,初始化weblogic相關(guān)配置。

 private void init_CheckWebLogicWorkaround(Container container) { 
  // test whether param-access workaround needs to be enabled 
  if (servletContext != null && servletContext.getServerInfo() != null 
                      && servletContext.getServerInfo().indexOf("WebLogic") >= 0) { 
  LOG.info("WebLogic server detected. Enabling Struts parameter access work-around."); 
      paramsWorkaroundEnabled = true; 
  } else { 
      paramsWorkaroundEnabled = "true".equals(container.getInstance(String.class, 
              StrutsConstants.STRUTS_DISPATCHER_PARAMETERSWORKAROUND)); 
  } 
  synchronized(Dispatcher.class) { 
      if (dispatcherListeners.size() > 0) { 
          for (DispatcherListener l : dispatcherListeners) { 
              l.dispatcherInitialized(this); 
          } 
      } 
  } 
 }

接著用FilterConfig類獲取wed.xml配置文件中的“packages”參數(shù),并獲取參數(shù)所有的JAVA包名的列表的值,并調(diào)用parse(packages)方法,將數(shù)它們的值一個(gè)一個(gè)的獲取到一個(gè)List對象中。

 protected String[] parse(String packages) { 
         if (packages == null) { 
             return null; 
         } 
         List<String> pathPrefixes = new ArrayList<String>(); 
         StringTokenizer st = new StringTokenizer(packages, ", \n\t"); 
         while (st.hasMoreTokens()) { 
             String pathPrefix = st.nextToken().replace('.', '/'); 
             if (!pathPrefix.endsWith("/")) { 
                 pathPrefix += "/"; 
             } 
             pathPrefixes.add(pathPrefix); 
         } 
         return pathPrefixes.toArray(new String[pathPrefixes.size()]); 
 }

1.1.2 doFilter方法的解釋,這方法實(shí)現(xiàn)了Action的調(diào)用。(最核心這個(gè)了)

 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 { 
      UtilTimerStack.push(timerKey); 
      request = prepareDispatcherAndWrapRequest(request, response); 
      ActionMapping mapping; 
      try { 
          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; 
      } 
      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")) { 
              findStaticResource(resourcePath, indAndCheckResources(resourcePath), request, response); 
          } else { 
              // this is a normal request, let it pass through 
              chain.doFilter(request, response); 
          } 
          // The framework did its job here 
          return; 
      } 
      dispatcher.serviceAction(request, response, servletContext, mapping); 
  } finally { 
      try { 
          ActionContextCleanUp.cleanUp(req); 
      } finally { 
          UtilTimerStack.pop(timerKey); 
      } 
  } 
 }

首先實(shí)例化HttpServletRequest、HttpServletResponse、ServletContext這些對象。 
接著調(diào)用UtilTimerStack.push()方法,但是搞不明這是有什么用的。 
接著調(diào)用prepareDispatcherAndWrapRequest()方法。

 protected HttpServletRequest prepareDispatcherAndWrapRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException { 
         Dispatcher du = Dispatcher.getInstance(); 
         if (du == null) { 
             Dispatcher.setInstance(dispatcher); 
             dispatcher.prepare(request, response); 
         } else { 
             dispatcher = du; 
         } 
         try { 
             request = dispatcher.wrapRequest(request, getServletContext()); 
         } catch (IOException e) { 
             String message = "Could not wrap servlet request with MultipartRequestWrapper!"; 
             LOG.error(message, e); 
             throw new ServletException(message, e); 
         } 
         return request; 
 }

首先調(diào)用Dispatcher.getInstance()靜態(tài)方法。在該方法中調(diào)用ThreadLocal類的get()方法,獲取當(dāng)前線程所對應(yīng)的線程局部變量。并通過它的返回,實(shí)例化一個(gè)Dispatcher對象。因此Struts2框架為每一個(gè)線程都提供了一個(gè)Dispatcher對象,所以在編寫Action的時(shí)候不需要考慮多線程的問題了。

 private static ThreadLocal<Dispatcher> instance = new ThreadLocal<Dispatcher>(); 
 public static Dispatcher getInstance() { 
         return instance.get(); 
 }

接著判斷du是否為空,如果是第一次訪問FilterDispatcher,那么du應(yīng)該為null,這時(shí)要調(diào)用Dispatcher的prepare()方法,在該方法中主要實(shí)現(xiàn)對編碼方式的設(shè)置。

 public void prepare(HttpServletRequest request, HttpServletResponse response) { 
         String encoding = null; 
         if (defaultEncoding != null) { 
             encoding = defaultEncoding; 
         } 
         Locale locale = null; 
         if (defaultLocale != null) { 
             locale = LocalizedTextUtil.localeFromString(defaultLocale, request.getLocale()); 
         } 
         if (encoding != null) { 
             try { 
                 request.setCharacterEncoding(encoding); 
             } catch (Exception e) { 
               LOG.error("Error setting character encoding to '" + encoding + "' - ignoring.", e); 
             } 
         } 
         if (locale != null) { 
             response.setLocale(locale); 
         } 
         if (paramsWorkaroundEnabled) { 
             request.getParameter("foo"); 
         } 
 }


接著調(diào)用dispatcher.wrapRequest(request, getServletContext())方法,對request對象進(jìn)行包裝(只需進(jìn)行一次)。判斷Content-Type是否是multipart/form-data,如果是的話返回一個(gè)MultiPartRequestWrapper的對象處理文件上傳,否則返回StrutsRequestWrapper的對象處理普通請求。

 public HttpServletRequest wrapRequest(HttpServletRequest request, 
 ServletContext servletContext) throws IOException { 
         if (request instanceof StrutsRequestWrapper) { 
             return request; 
         } 
         String content_type = request.getContentType(); 
         if (content_type != null && content_type.indexOf("multipart/form-data") != -1) { 
             MultiPartRequest multi = getContainer().getInstance(MultiPartRequest.class); 
             request = new MultiPartRequestWrapper(multi, request, 
 getSaveDir(servletContext)); 
         } else { 
             request = new StrutsRequestWrapper(request); 
         } 
         return request; 
 }

○1MultiPartRequestWrapper類的解釋(網(wǎng)上找的解釋,覺得很全,所以就用了拿來主義了) 
Struts2的MultiPartRequestWrapper來分離請求中的數(shù)據(jù)。(注意:向服務(wù)器請求時(shí),數(shù)據(jù)是以流的形式向服務(wù)器提交,內(nèi)容是一些有規(guī)則東東,我們平時(shí)在jsp中用request內(nèi)置對象取parameter時(shí),實(shí)際上是由tomcat的HttpServletRequestWrapper類分解好了的,無需我們再分解這些東西了。)
MultiPartRequestWrapper這個(gè)類是Struts2的類,并且繼承了tomcat的HttpServletRequestWrapper類,也是我們將用來代替HttpServletRequest這個(gè)類的類,看名字也知道,是對多媒體請求的包裝類。Struts2本身當(dāng)然不會再造個(gè)輪子,來解析請求,而是交由Apache的commons-fileupload組件來解析了。 
在MultiPartRequestWrapper的構(gòu)造方法中,會調(diào)用MultiPartRequest(默認(rèn)為JakartaMultiPartRequest類)的parse方法來解析請求。 
在Struts2的JakartaMultiPartRequest類的parse方法中才會真正來調(diào)用commons-fileupload組 件的ServletFileUpload類對請求進(jìn)行解析,至此,Struts2已經(jīng)實(shí)現(xiàn)了將請求轉(zhuǎn)交commons-fileupload組件對請求解 析的全過程。剩下的就是等commons-fileupload組件對請求解析完畢后,拿到分解后的數(shù)據(jù),根據(jù)field名,依次將分解后的field名 和值放到params(HashMap類型)里,同時(shí)JakartaMultiPartRequest類重置了HttpServletRequest的好 多方法,比如熟知的getParameter、getParameterNames、getParameterValues,實(shí)際上都是從解析后得到的那 個(gè)params對象里拿數(shù)據(jù),在這個(gè)過程,commons-fileupload組件也乖乖的把上傳的文件分析好 了,JakartaMultiPartRequest也毫不客氣的把分解后的文件一個(gè)一個(gè)的放到了files(HashMap類型)中,實(shí)際上此 時(shí),commons-fileupload組件已經(jīng)所有要上傳的文件上傳完了。至此,Struts2實(shí)現(xiàn)了對HttpServletRequest類的包 裝,當(dāng)回到MultiPartRequestWrapper類后,再取一下上述解析過程中發(fā)生的錯(cuò)誤,然后把錯(cuò)誤加到了自己的errors列表中了。同樣我們會發(fā)現(xiàn)在MultiPartRequestWrapper類中,也把HttpServletRequest類的好多方法重載了,畢竟是個(gè)包裝類嘛,實(shí)際上對于上傳文件的請求,在Struts2后期的處理中用到的request都是MultiPartRequestWrapper類對象,比如我們調(diào)用getParameter時(shí),直接調(diào)用的是MultiPartRequestWrapper的getParameter方法,間接調(diào)的是JakartaMultiPartRequest類對象的getParameter方法。(注:從這里,我們就可以看出,JakartaMultiPartRequest是完全設(shè)計(jì)成可以替換的類了。 )

接著ActionMapper.getMapping(), ActionMapper類是一個(gè)接口類,其具體實(shí)現(xiàn)是由DefaultActionMapper類實(shí)現(xiàn)的。以便確定這個(gè)請求是否有對應(yīng)的action調(diào)用。

 DefaultActionMapper類中的getMapping()方法 
 public ActionMapping getMapping(HttpServletRequest request, 
                                            ConfigurationManager configManager) { 
         ActionMapping mapping = new ActionMapping(); 
         String uri = getUri(request); 
         uri = dropExtension(uri); 
         if (uri == null) { 
             return null; 
         } 
         parseNameAndNamespace(uri, mapping, configManager); 
         handleSpecialParameters(request, mapping); 
         if (mapping.getName() == null) { 
             return null; 
         } 
         if (allowDynamicMethodCalls) { 
             // handle "name!method" convention. 
             String name = mapping.getName(); 
             int exclamation = name.lastIndexOf("!"); 
             if (exclamation != -1) { 
                 mapping.setName(name.substring(0, exclamation)); 
                 mapping.setMethod(name.substring(exclamation + 1)); 
             } 
         } 
         return mapping; 
 }

首先創(chuàng)建一個(gè)ActionMapping對象(關(guān)于ActionMapping類,它內(nèi)部封裝了如下5個(gè)字段)

private String name;// Action名  
private String namespace;// Action名稱空間  
private String method;// 執(zhí)行方法  
private Map params;// 可以通過set方法設(shè)置的參數(shù)  
private Result result;// 返回的結(jié)果 
這些參數(shù)在配置文件中都是可設(shè)置的,確定了ActionMapping類的各個(gè)字段的值,就可以對請求的Action進(jìn)行調(diào)用了。

接著調(diào)getUri(request)方法,它主要實(shí)現(xiàn)獲取請求的URI。這個(gè)方法首先判斷請求是否來自于一個(gè)jsp的include,如果是,那么請求 的"javax.servlet.include.servlet_path"屬性可以獲得include的頁面uri,否則通過一般的方法獲得請求的 uri,最后返回去掉ContextPath的請求路徑,比如http://127.0.0.1:8087/test/jsp /index.jsp?param=1,返回的為/jsp/index.jsp。去掉了ContextPath和查詢字符串等。

 String getUri(HttpServletRequest request) { 
         String uri = (String) 
                  request .getAttribute("javax.servlet.include.servlet_path"); 
         if (uri != null) { 
             return uri; 
         } 
         uri = RequestUtils.getServletPath(request); 
         if (uri != null && !"".equals(uri)) { 
             return uri; 
         } 
         uri = request.getRequestURI(); 
         return uri.substring(request.getContextPath().length()); 
}

接著調(diào)用dropExtension(uri)方法,該方法負(fù)責(zé)去掉Action的"擴(kuò)展名"(默認(rèn)為"action")

 String dropExtension(String name) { 
         if (extensions == null) { 
             return name; 
         } 
         Iterator it = extensions.iterator(); 
         while (it.hasNext()) { 
             String extension = "." + (String) it.next(); 
             if (name.endsWith(extension)) { 
                 name = name.substring(0, name.length() - extension.length()); 
                 return name; 
             } 
         } 
         return null; 
 }

接著調(diào)用parseNameAndNamespace()方法, 此方法用于解析Action的名稱和命名空間,并賦給ActionMapping對象。

 void parseNameAndNamespace(String uri, ActionMapping mapping, 
 ConfigurationManager configManager) {  
 String namespace, name;  
 /* 例如 http://127.0.0.1:8087/teststruts/namespace/name.action?param=1 */  
 /* dropExtension()后,獲得uri為/namespace/name */  
        int lastSlash = uri.lastIndexOf("/");  
        if (lastSlash == -1) {  
           namespace = "";  
            name = uri;  
        } else if (lastSlash == 0) {  
            namespace = "/";  
            name = uri.substring(lastSlash + 1);  
        } else if (alwaysSelectFullNamespace) { 
  // alwaysSelectFullNamespace默認(rèn)為false,代表是否將最后一個(gè)"/"前的字符全作為名稱空間。  
            namespace = uri.substring(0, lastSlash);// 獲得字符串 namespace  
            name = uri.substring(lastSlash + 1);// 獲得字符串 name  
        } else {  
     /* 例如 http://127.0.0.1:8087/teststruts/namespace1/namespace2/ 
   actionname.action?param=1 */  
      /* dropExtension()后,獲得uri為/namespace1/namespace2/actionname */  
            Configuration config = configManager.getConfiguration();  
            String prefix = uri.substring(0, lastSlash); 
  // 獲得 /namespace1/namespace2  
            namespace = "";  
            /*如果配置文件中有一個(gè)包的namespace是 /namespace1/namespace2, 
  那么namespace為/namespace1/namespace2,name為actionname  */ 
            /* 如果配置文件中有一個(gè)包的namespace是 /namespace1, 
  那么namespace為/namespace1,name為/namespace2/actionname*/  
      for (Iterator i = config.getPackageConfigs().values().iterator(); i.hasNext();) {  
                String ns = ((PackageConfig) i.next()).getNamespace();  
                if (ns != null && prefix.startsWith(ns) && (prefix.length() == ns.length() || prefix.charAt(ns.length()) == '/')) {  
                    if (ns.length() > namespace.length()) {  
                        namespace = ns;  
                    }  
                }  
            }  
              name = uri.substring(namespace.length() + 1);  
        }  
          if (!allowSlashesInActionNames && name != null) { 
  //allowSlashesInActionNames代表是否允許"/"出現(xiàn)在Action的名稱中,默認(rèn)為false  
            int pos = name.lastIndexOf('/');  
            if (pos > -1 && pos < name.length() - 1) {  
                name = name.substring(pos + 1);  
            }  
        } 
  // 以 name = /namespace2/actionname 為例,經(jīng)過這個(gè)if塊后,name = actionname  
        mapping.setNamespace(namespace);  
        mapping.setName(name);  
  }

接著調(diào)用handleSpecialParameters()方法, 該方法將請求參數(shù)中的重復(fù)項(xiàng)去掉.(但該方法存在問題,具體原因見“由IE瀏覽器引發(fā)的Struts2的Bug(submit無法傳至服務(wù)器).doc”)

 public void handleSpecialParameters(HttpServletRequest request, 
             ActionMapping mapping) { 
         // handle special parameter prefixes. 
         Set<String> uniqueParameters = new HashSet<String>(); 
         Map parameterMap = request.getParameterMap(); 
         for (Iterator iterator = parameterMap.keySet().iterator(); iterator 
                 .hasNext();) { 
             String key = (String) iterator.next(); 
             // Strip off the image button location info, if found 
             if (key.endsWith(".x") || key.endsWith(".y")) { 
                 key = key.substring(0, key.length() - 2); 
             }            
             // Ensure a parameter doesn't get processed twice 
             if (!uniqueParameters.contains(key)) { 
                 ParameterAction parameterAction = (ParameterAction) prefixTrie 
                         .get(key); 
                 if (parameterAction != null) { 
                     parameterAction.execute(key, mapping); 
                     uniqueParameters.add(key); 
                     break; 
                 } 
             } 
         } 
 }

接著判斷Action的name有沒有解析出來,如果沒,直接返回NULL。

 if (mapping.getName() == null) { 
       returnnull; 
 }

最后處理形如testAction!method格式的請求路徑。

 if (allowDynamicMethodCalls) { 
     // handle "name!method" convention. 
     String name = mapping.getName(); 
     int exclamation = name.lastIndexOf("!"); 
     //!是Action名稱和方法名的分隔符 
     if (exclamation != -1) { 
         mapping.setName(name.substring(0, exclamation)); 
         //提取左邊為name 
         mapping.setMethod(name.substring(exclamation + 1)); 
         //提取右邊的method 
     } 
 }

ActionMapper.getMapping()流程圖:

從代碼中看出,getMapping()方法返回ActionMapping類型的對象,該對象包含三個(gè)參數(shù):Action的name、namespace和要調(diào)用的方法method。 
接著,判斷如果getMapping()方法返回ActionMapping對象為null,則FilterDispatcher認(rèn)為用戶請求不是Action, 自然另當(dāng)別論,F(xiàn)ilterDispatcher會做一件非常有意思的事:如果請求以/struts開頭,會自動查找在web.xml文件中配置的 packages初始化參數(shù),就像下面這樣(注意粗斜體部分): 
   <filter> 
     <filter-name>struts2</filter-name> 
     <filter-class> 
       org.apache.struts2.dispatcher.FilterDispatcher 
     </filter-class> 
     <init-param> 
       <param-name>packages</param-name> 
       <param-value>com.lizanhong.action</param-value> 
     </init-param> 
   </filter> 
   FilterDispatcher會將com.lizanhong.action包下的文件當(dāng)作靜態(tài)資源處理,(但是Struts2.0和Struts2.1對其處理不同)Struts2.0只會顯示出錯(cuò)信息,而Struts2.1接在頁面上顯示文件內(nèi)容,不過會忽略 擴(kuò)展名為class的文件。比如在com.lizanhong.action包下有一個(gè)aaa.txt的文本文件,其內(nèi)容為“中華人民共和國”,訪問 http://localhost:8081/Struts2Demo/struts/aaa.txt時(shí)會有如下圖的輸出


FilterDispatcher.findStaticResource()方法,就是負(fù)責(zé)查找靜態(tài)資源的方法。 
接著,如getMapping()方法返回ActionMapping對象不為null,則認(rèn)為正在請求某個(gè)Action,并且運(yùn)行dispatcher.serviceAction(request, response, servletContext, mapping)方法,該方法是ACTION處理的核心。在Dispatcher.serviceAction()方法中,先加載Struts2的配置文件,如果沒有人為配置,則默認(rèn)加載struts- default.xml、struts-plugin.xml和struts.xml,并且將配置信息保存在形如 com.opensymphony.xwork2.config.entities.XxxxConfig的類中。

 public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,ActionMapping mapping) throws ServletException { 
         Map<String, Object> extraContext = createContextMap(request, response, mapping, context); 
         ValueStack stack = (ValueStack) request .getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY); 
         if (stack != null) { 
             extraContext.put(ActionContext.VALUE_STACK, ValueStackFactory.getFactory().createValueStack(stack)); 
         } 
         String timerKey = "Handling request from Dispatcher"; 
         //"Handling request from Dispatcher"表示處理請求調(diào)度 
         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, extraContext, true, false); 
             proxy.setMethod(method); 
             request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack()); 
             if (mapping.getResult() != null) { 
                 Result result = mapping.getResult(); 
                 result.execute(proxy.getInvocation()); 
             } else { 
                 proxy.execute(); 
             } 
             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) { 
             throw new ServletException(e); 
         } finally { 
             UtilTimerStack.pop(timerKey); 
         } 
 }

首先調(diào)用createContextMap()方法,這個(gè)方法首先創(chuàng)建了一個(gè)名稱為extraContext的Map對象。它保存了request,session,application,mapping的信息,這些信息以后可以統(tǒng)一在此對象中查找。

 Public Map<String,Object> createContextMap(HttpServletRequest request, 
 HttpServletResponse response,ActionMapping mapping, ServletContext context) {  
       Map requestMap = new RequestMap(request);// 封裝了請求對象  
       Map params = null;// 封裝了http參數(shù)  
     if (mapping != null) {  
         params = mapping.getParams();//從ActionMapping中獲取Action的參數(shù)Map  
     }  
      Map requestParams = new HashMap(request.getParameterMap());  
     if (params != null) {  
         params.putAll(requestParams);// 并將請求中的參數(shù)也放入Map中  
     } else {  
         params = requestParams;  
     }  
     Map session = new SessionMap(request);// 封裝了session  
     Map application = new ApplicationMap(context);// 封裝了ServletContext  
     /*將各個(gè)Map放入extraContext中 */  
    Map<String,Object> extraContext = createContextMap(requestMap, params, session, application, request, response, context);  
     extraContext.put(ServletActionContext.ACTION_MAPPING, mapping);  
     return extraContext;  
 } 

接著判斷request中是否已經(jīng)有了一個(gè)ValueStack對象,將其保存下來,留待以后恢復(fù),并把它進(jìn)行一些封裝后也存入extraContext中。 
接下來是一些準(zhǔn)備工作,如,獲取了namespace,name,method等。 
接著構(gòu)建一個(gè)ActionProxy對象,它負(fù)責(zé)對真實(shí)的Action進(jìn)行調(diào)用,并可以在調(diào)用Action前后調(diào)用攔截器(Interceptor),其默認(rèn)實(shí)現(xiàn)StrutsActionProxyFactory類中的createActionProxy()方法。

 public ActionProxy createActionProxy(String namespace, String actionName, 
 Map extraContext,boolean executeResult, boolean cleanupContext)throws Exception { 
         ActionProxy proxy = new StrutsActionProxy(namespace, actionName, extraContext, executeResult, cleanupContext); 
         container.inject(proxy); 
         proxy.prepare(); 
         return proxy; 
 }

由上述的源代碼可見,方法返回了一個(gè)StrutsActionProxy對象作為ActionProxy的默認(rèn)實(shí)現(xiàn)。 
其中proxy.prepare()方法,是用DefaultActionProxy類中的prepare()默認(rèn)實(shí)現(xiàn)。

 public void prepare() throws Exception { 
  String profileKey = "create DefaultActionProxy: "; 
  try { 
      UtilTimerStack.push(profileKey); 
      config = configuration.getRuntimeConfiguration().getActionConfig(namespace, actionName); 
      if (config == null && unknownHandler != null) { 
          config = unknownHandler.handleUnknownAction(namespace, actionName); 
      } 
      if (config == null) { 
          String message; 
          if ((namespace != null) && (namespace.trim().length() > 0)) { 
              message = calizedTextUtil.findDefaultText(XWorkMessages.MISSING_PACKAGE_ACTION_EXCEPTION, Locale.getDefault(), new String[]{ 
                  namespace, actionName 
              }); 
          } else { 
              message = LocalizedTextUtil.findDefaultText(XWorkMessages.MISSING_ACTION_EXCEPTION, Locale.getDefault(), new String[]{ 
                  actionName 
              }); 
          } 
          throw new ConfigurationException(message); 
      } 
      
      invocation = new DefaultActionInvocation(objectFactory, unknownHandler, this, extraContext, true, actionEventListener); 
      resolveMethod(); 
  } finally { 
      UtilTimerStack.pop(profileKey); 
  } 
 }

這里邊創(chuàng)建了一個(gè)DefaultActionInvocation對象作為ActionInvocation對象的默認(rèn)實(shí)現(xiàn)。

接著調(diào)用resolveMethod()方法 
 private void resolveMethod() { 
         if (!TextUtils.stringSet(this.method)) { 
             this.method = config.getMethodName(); 
             if (!TextUtils.stringSet(this.method)) { 
                 this.method = "execute"; 
             } 
         } 
 }

這個(gè)方法實(shí)現(xiàn)了Action執(zhí)行方法的設(shè)定,如果config中配置有方法名,那么就將這個(gè)方法名作為執(zhí)行方法名,否則就用默認(rèn)的execute。

接著運(yùn)行proxy.setMethod(method)語句,這里主要為了設(shè)置Action調(diào)用中要執(zhí)行的方法.如果沒有方法被指定,將會由Action的配置來提供. 
接著運(yùn)行 request.setAttribute()方法,把ValueStack對象放在Request對象中,以便通過Request對象訪問ValueStack中的對象. 
接著判斷ActionMapping.getResult()是否為空,如果不為空,則獲取相關(guān)Result對象. 
接著執(zhí)行result.execute(proxy.getInvocation())方法.在proxy.getInvocation()方法的默認(rèn)實(shí)現(xiàn)是DefaultActionProxy類的getInvocation()方法. getInvocation()方法獲取一個(gè)DefaultActionInvocation對象, DefaultActionInvocation對象在定義了invoke()方法,該方法實(shí)現(xiàn)了截?cái)r器的遞歸調(diào)用和執(zhí)行Action的執(zhí)行方法(如execute()方法). 
如果不為空, 執(zhí)行proxy.execute()方法. ActionProxy類是通過DefaultActionProxy類來具體實(shí)現(xiàn)的.

 public String execute() throws Exception { 
         ActionContext nestedContext = ActionContext.getContext(); 
         ActionContext.setContext(invocation.getInvocationContext()); 
         String retCode = null; 
         String profileKey = "execute: "; 
         try { 
         UtilTimerStack.push(profileKey); 
             retCode = invocation.invoke(); 
         } finally { 
             if (cleanupContext) { 
                 ActionContext.setContext(nestedContext); 
             } 
             UtilTimerStack.pop(profileKey); 
         } 
         return retCode; 
 } 
在其中調(diào)用了ActionInvocation類的invoke()方法,而其具體實(shí)現(xiàn)是由DefaultActionInvocation類的invoke()方法實(shí)現(xiàn)的. 該方法實(shí)現(xiàn)了截?cái)r器的遞歸調(diào)用和執(zhí)行Action的execute()方法. 
 public String invoke() throws Exception {
  String profileKey = "invoke: ";
  try {
   UtilTimerStack.push(profileKey);
   if (executed) {
    throw new IllegalStateException("Action has already executed");
   }
   if (interceptors.hasNext()) {
    //從截?cái)r器集合中取出當(dāng)前的截?cái)r器 
    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 {
    resultCode = invokeActionOnly();
   }
   if (!executed) {
    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);
      }
     }
    }
    if (proxy.getExecuteResult()) {
     executeResult();
    }
    executed = true;
   }
   return resultCode;
  } finally {
   UtilTimerStack.pop(profileKey);
  }
 }
}

在上述代碼實(shí)現(xiàn)遞歸調(diào)用截?cái)r器是由Interceptor 類來實(shí)現(xiàn)的.

 publicinterface Interceptor extends Serializable { 
   void destroy(); 
   void init(); 
   String intercept(ActionInvocation invocation) throws Exception; 
 }

所有的截?cái)r器必須實(shí)現(xiàn)intercept方法,而該方法的參數(shù)恰恰又是ActionInvocation,所以,如果在intercept方法中調(diào)用 invocation.invoke(),invoke()方法中藍(lán)色代碼會再次執(zhí)行,從Action的Intercepor列表中找到下一個(gè)截?cái)r器,依此遞歸. 
調(diào)用流程如下:

如果截?cái)r器全部執(zhí)行完畢,則調(diào)用invokeActionOnly()方法執(zhí)行Action,invokeActionOnly()方法基本沒做什么工作,只調(diào)用了invokeAction()方法。

public String invokeActionOnly() throws Exception { 
    return invokeAction(getAction(), proxy.getConfig()); 
}

DefaultActionInvocation.invokeAction()方法實(shí)現(xiàn)Action的調(diào)用. 
 protected String invokeAction(Object action, ActionConfig actionConfig)
   throws Exception {
  String methodName = proxy.getMethod();
  if (LOG.isDebugEnabled()) {
   LOG.debug("Executing action method = "
     + actionConfig.getMethodName());
  }
  String timerKey = "invokeAction: " + proxy.getActionName();
  try {
   UtilTimerStack.push(timerKey);
   Method method;
   try {
    method = getAction().getClass().getMethod(methodName,new Class[0]);
   } catch (NoSuchMethodException e) {
    try {
     String altMethodName = "do"+ methodName.substring(0, 1).toUpperCase()+ methodName.substring(1);
     method = getAction().getClass().getMethod(altMethodName,new Class[0]);
    } catch (NoSuchMethodException e1) {
     throw e;
    }
   }
   Object methodResult = method.invoke(action, new Object[0]);
   if (methodResult instanceof Result) {
    this.result = (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) {
   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);
  }
 }

由這句Object methodResult = method.invoke(action, new Object[0]);可以看出,最后通過反射實(shí)現(xiàn)了Action的執(zhí)行方法的調(diào)用。

接著返回invoke()方法,判斷executed是否為false.如果是則調(diào)用了在PreResultListener中的定義的一些執(zhí)行Result前的操作. 
接著根據(jù)配置文件中的設(shè)置執(zhí)行Result.其執(zhí)行方法為executeResult()方法.

 private void executeResult() throws Exception {
  result = createResult();
  String timerKey = "executeResult: " + getResultCode();
  try {
   UtilTimerStack.push(timerKey);
   if (result != null) {
    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);
  }
 } 
然后,返回到dispatcher.serviceAction()方法,完成調(diào)用.

    本站是提供個(gè)人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多