最近作java開發,須要用到相關開源框架。java
在學習struts2以前,首先咱們要明白使用struts2的目的是什麼?它能給咱們帶來什麼樣的好處?web
Struts設計的第一目標就是使MVC模式應用於web程序設計。在這兒MVC模式的好處就不在提了。spring
Struts2有兩方面的技術優點,一是全部的Struts2應用程序都是基於client/server HTTP交換協議,The Java Servlet API揭示了Java Servlet只是Java API的一個很小子集,這樣咱們能夠在業務邏輯部分使用功能強大的Java語言進行程序設計。apache
二是提供了對MVC的一個清晰的實現,這一實現包含了不少參與對因此請求進行處理的關鍵組件,如:攔截器、OGNL表達式語言、堆棧。json
由於struts2有這樣目標,而且有這樣的優點,因此,這是咱們學習struts2的理由,下面,咱們在深刻剖析一下struts的工做原理。設計模式
Suruts2的工做原理能夠用下面這張圖來描述,下面咱們分步驟介紹一下每一步的核心內容api
一個請求在Struts2框架中的處理大概分爲如下幾個步驟 安全
一、客戶端初始化一個指向Servlet容器(例如Tomcat)的請求session
二、這個請求通過一系列的過濾器(Filter)(這些過濾器中有一個叫作ActionContextCleanUp的可選過濾器,這個過濾器對於Struts2和其餘框架的集成頗有幫助,例如:SiteMesh Plugin) mvc
三、接着FilterDispatcher被調用,FilterDispatcher詢問ActionMapper來決定這個請是否須要調用某個Action
FilterDispatcher是控制器的核心,就是mvc中c控制層的核心。下面粗略的分析下我理解的FilterDispatcher工做流程和原理:FilterDispatcher進行初始化並啓用核心doFilter
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException ...{ HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; ServletContext servletContext = filterConfig.getServletContext(); // 在這裏處理了HttpServletRequest和HttpServletResponse。 DispatcherUtils du = DispatcherUtils.getInstance(); du.prepare(request, response);//正如這個方法名字同樣進行locale、encoding以及特殊request parameters設置 try ...{ request = du.wrapRequest(request, servletContext);//對request進行包裝 } catch (IOException e) ...{ String message = "Could not wrap servlet request with MultipartRequestWrapper!"; LOG.error(message, e); throw new ServletException(message, e); } ActionMapperIF mapper = ActionMapperFactory.getMapper();//獲得action的mapper ActionMapping mapping = mapper.getMapping(request);// 獲得action 的 mapping 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 ("true".equals(Configuration.get(WebWorkConstants.WEBWORK_SERVE_STATIC_CONTENT)) && resourcePath.startsWith("/webwork")) ...{ String name = resourcePath.substring("/webwork".length()); findStaticResource(name, response); } else ...{ // this is a normal request, let it pass through chain.doFilter(request, response); } // WW did its job here return; } Object o = null; try ...{ //setupContainer(request); o = beforeActionInvocation(request, servletContext); //整個框架最最核心的方法,下面分析 du.serviceAction(request, response, servletContext, mapping); } finally ...{ afterActionInvocation(request, servletContext, o); ActionContext.setContext(null); } } du.serviceAction(request, response, servletContext, mapping); //這個方法詢問ActionMapper是否須要調用某個Action來處理這個(request)請求,若是ActionMapper決定須要調用某個Action,FilterDispatcher把請求的處理交給ActionProxy public void serviceAction(HttpServletRequest request, HttpServletResponse response, String namespace, String actionName, Map requestMap, Map parameterMap, Map sessionMap, Map applicationMap) ...{ HashMap extraContext = createContextMap(requestMap, parameterMap, sessionMap, applicationMap, request, response, getServletConfig()); //實例化Map請求 ,詢問ActionMapper是否須要調用某個Action來處理這個(request)請求 extraContext.put(SERVLET_DISPATCHER, this); OgnlValueStack stack = (OgnlValueStack) request.getAttribute(ServletActionContext.WEBWORK_VALUESTACK_KEY); if (stack != null) ...{ extraContext.put(ActionContext.VALUE_STACK,new OgnlValueStack(stack)); } try ...{ ActionProxy proxy = ActionProxyFactory.getFactory().createActionProxy(namespace, actionName, extraContext); //這裏actionName是經過兩道getActionName解析出來的, FilterDispatcher把請求的處理交給ActionProxy,下面是ServletDispatcher的 TODO: request.setAttribute(ServletActionContext.WEBWORK_VALUESTACK_KEY, proxy.getInvocation().getStack()); proxy.execute(); //經過代理模式執行ActionProxy if (stack != null)...{ request.setAttribute(ServletActionContext.WEBWORK_VALUESTACK_KEY,stack); } } catch (ConfigurationException e) ...{ log.error("Could not find action", e); sendError(request, response, HttpServletResponse.SC_NOT_FOUND, e); } catch (Exception e) ...{ log.error("Could not execute action", e); sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e); } }
四、若是ActionMapper決定須要調用某個Action,FilterDispatcher把請求的處理交給ActionProxy
五、ActionProxy經過ConfigurationManager詢問框架的配置文件,找到須要調用的Action類 ,這裏,咱們通常是從struts.xml配置中讀取。
六、ActionProxy建立一個ActionInvocation的實例。
七、ActionInvocation實例使用命名模式來調用,在調用Action的過程先後,涉及到相關攔截器(Intercepter)的調用。
下面咱們來看看ActionInvocation是如何工做的:
ActionInvocation是Xworks 中Action 調度的核心。而對Interceptor 的調度,也正是由ActionInvocation負責。ActionInvocation 是一個接口,而DefaultActionInvocation 則是Webwork 對ActionInvocation的默認實現。
Interceptor的調度流程大體以下:
1.ActionInvocation初始化時,根據配置,加載Action相關的全部Interceptor。
2. 經過ActionInvocation.invoke方法調用Action實現時,執行Interceptor。
Interceptor將不少功能從咱們的Action中獨立出來,大量減小了咱們Action的代碼,獨立出來的行爲具備很好的重用性。XWork、WebWork的許多功能都是有Interceptor實現,能夠在配置文件中組裝Action用到的Interceptor,它會按照你指定的順序,在Action執行先後運行。
這裏,咱們簡單的介紹一下Interceptor
在struts2中自帶了不少攔截器,在struts2-core-2.1.6.jar這個包下的struts-default.xml中咱們能夠發現:
<interceptors> <interceptor name="alias"class="com.opensymphony.xwork2.interceptor.AliasInterceptor"/> <interceptor name="autowiring"class="com.opensymphony.xwork2.spring.interceptor.ActionAutowiringInterceptor"/> <interceptor name="chain"class="com.opensymphony.xwork2.interceptor.ChainingInterceptor"/> <interceptor name="conversionError"class="org.apache.struts2.interceptor.StrutsConversionErrorInterceptor"/> <interceptor name="clearSession"class="org.apache.struts2.interceptor.ClearSessionInterceptor"/> <interceptor name="createSession"class="org.apache.struts2.interceptor.CreateSessionInterceptor"/> <interceptor name="debugging"class="org.apache.struts2.interceptor.debugging.DebuggingInterceptor"/> <interceptor name="externalRef"class="com.opensymphony.xwork2.interceptor.ExternalReferencesInterceptor"/> <interceptor name="execAndWait"class="org.apache.struts2.interceptor.ExecuteAndWaitInterceptor"/> <interceptor name="exception"class="com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor"/> <interceptor name="fileUpload"class="org.apache.struts2.interceptor.FileUploadInterceptor"/> <interceptor name="i18n"class="com.opensymphony.xwork2.interceptor.I18nInterceptor"/> <interceptor name="logger"class="com.opensymphony.xwork2.interceptor.LoggingInterceptor"/> <interceptor name="modelDriven"class="com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor"/> <interceptor name="scopedModelDriven"class="com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor"/> <interceptor name="params"class="com.opensymphony.xwork2.interceptor.ParametersInterceptor"/> <interceptor name="actionMappingParams"class="org.apache.struts2.interceptor.ActionMappingParametersInteceptor"/> <interceptor name="prepare"class="com.opensymphony.xwork2.interceptor.PrepareInterceptor"/> <interceptor name="staticParams"class="com.opensymphony.xwork2.interceptor.StaticParametersInterceptor"/> <interceptor name="scope"class="org.apache.struts2.interceptor.ScopeInterceptor"/> <interceptor name="servletConfig"class="org.apache.struts2.interceptor.ServletConfigInterceptor"/> <interceptor name="sessionAutowiring"class="org.apache.struts2.spring.interceptor.SessionContextAutowiringInterceptor"/> <interceptor name="timer"class="com.opensymphony.xwork2.interceptor.TimerInterceptor"/> <interceptor name="token"class="org.apache.struts2.interceptor.TokenInterceptor"/> <interceptor name="tokenSession"class="org.apache.struts2.interceptor.TokenSessionStoreInterceptor"/> <interceptor name="validation"class="org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor"/> <interceptor name="workflow"class="com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor"/> <interceptor name="store"class="org.apache.struts2.interceptor.MessageStoreInterceptor"/> <interceptor name="checkbox"class="org.apache.struts2.interceptor.CheckboxInterceptor"/> <interceptor name="profiling"class="org.apache.struts2.interceptor.ProfilingActivationInterceptor"/> <interceptor name="roles"class="org.apache.struts2.interceptor.RolesInterceptor"/> <interceptor name="jsonValidation"class="org.apache.struts2.interceptor.validation.JSONValidationInterceptor"/> <interceptorname="annotationWorkflow"class="com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor"/>
對於sturts2自帶的攔截器,使用起來就相對比較方便了,咱們只須要在struts.xml的action標籤中加入<interceptor-ref name=" logger " />而且struts.xml擴展struts-default,就可使用,
若是是要自定義攔截器,首先須要寫一個攔截器的類:
package ceshi; import com.opensymphony.xwork2.ActionInvocation; import com.opensymphony.xwork2.interceptor.AbstractInterceptor; publicclassAuthorizationInterceptor extends AbstractInterceptor { @Override public Stringintercept(ActionInvocation ai)throws Exception { System.out.println("abc"); return ai.invoke(); } }
而且在struts.xml中進行配置
<!DOCTYPEstruts PUBLIC "-//Apache SoftwareFoundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="test"extends="struts-default"> <interceptors> <interceptor name="abc"class ="ceshi.AuthorizationInterceptor"/> </interceptors> <action name="TestLogger"class="vaannila.TestLoggerAction"> <interceptor-refname="abc"/> <result name="success">/success.jsp</result> </action> </package> </struts>
八、一旦Action執行完畢,ActionInvocation負責根據struts.xml中的配置找到對應的返回結果。返回結果一般是(但不老是,也多是另外的一個Action鏈)一個須要被表示的JSP或者FreeMarker的模版。在表示的過程當中可使用Struts2 框架中繼承的標籤。在這個過程當中須要涉及到ActionMapper
在上述過程當中全部的對象(Action,Results,Interceptors,等)都是經過ObjectFactory來建立的。
struts2相對於struts1來講簡單了不少,而且功能強大了不少,咱們能夠從幾個方面來看:
從體系結構來看:struts2大量使用攔截器來出來請求,從而容許與業務邏輯控制器 與 servlet-api分離,避免了侵入性;而struts1.x在action中明顯的侵入了servlet-api.
從線程安全分析:struts2.x是線程安全的,每個對象產生一個實例,避免了線程安全問題;而struts1.x在action中屬於單線程。
性能方面:struts2.x測試能夠脫離web容器,而struts1.x依賴servlet-api,測試須要依賴web容器。
請求參數封裝對比:struts2.x使用ModelDriven模式,這樣咱們 直接 封裝model對象,無須要繼承任何struts2的基類,避免了侵入性。
標籤的優點:標籤庫幾乎能夠徹底替代JSTL的標籤庫,而且 struts2.x支持強大的ognl表達式。
固然,struts2和struts1相比,在 文件上傳,數據校驗 等方面也 方便了好多。在這就不詳談了。
一個比較優秀的框架能夠幫着咱們更高效,穩定的開發合格的產品,不過咱們也不要依賴框架,咱們只要理解了思想,設計模式,咱們能夠本身擴展功能,否則 就要 永遠讓別人牽着走了!
轉自:連接