最近做java開(kāi)發(fā),需要用到相關(guān)開(kāi)源框架。
在學(xué)習(xí)struts2之前,首先我們要明白使用struts2的目的是什么?它能給我們帶來(lái)什么樣的好處?
Struts設(shè)計(jì)的第一目標(biāo)就是使MVC模式應(yīng)用于web程序設(shè)計(jì)。在這兒MVC模式的好處就不在提了。
Struts2有兩方面的技術(shù)優(yōu)勢(shì),一是所有的Struts2應(yīng)用程序都是基于client/server HTTP交換協(xié)議,The Java Servlet API揭示了Java Servlet只是Java API的一個(gè)很小子集,這樣我們可以在業(yè)務(wù)邏輯部分使用功能強(qiáng)大的Java語(yǔ)言進(jìn)行程序設(shè)計(jì)。
二是提供了對(duì)MVC的一個(gè)清晰的實(shí)現(xiàn),這一實(shí)現(xiàn)包含了很多參與對(duì)所以請(qǐng)求進(jìn)行處理的關(guān)鍵組件,如:攔截器、OGNL表達(dá)式語(yǔ)言、堆棧。
因?yàn)閟truts2有這樣目標(biāo),并且有這樣的優(yōu)勢(shì),所以,這是我們學(xué)習(xí)struts2的理由,下面,我們?cè)谏钊肫饰鲆幌聅truts的工作原理。
Suruts2的工作原理可以用下面這張圖來(lái)描述,下面我們分步驟介紹一下每一步的核心內(nèi)容
一個(gè)請(qǐng)求在Struts2框架中的處理大概分為以下幾個(gè)步驟
1、客戶端初始化一個(gè)指向Servlet容器(例如Tomcat)的請(qǐng)求
2、這個(gè)請(qǐng)求經(jīng)過(guò)一系列的過(guò)濾器(Filter)(這些過(guò)濾器中有一個(gè)叫做ActionContextCleanUp的可選過(guò)濾器,這個(gè)過(guò)濾器對(duì)于Struts2和其他框架的集成很有幫助,例如:SiteMesh Plugin)
3、接著FilterDispatcher被調(diào)用,F(xiàn)ilterDispatcher詢問(wèn)ActionMapper來(lái)決定這個(gè)請(qǐng)是否需要調(diào)用某個(gè)Action
FilterDispatcher是控制器的核心,就是mvc中c控制層的核心。下面粗略的分析下我理解的FilterDispatcher工作流程和原理:FilterDispatcher進(jìn)行初始化并啟用核心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);//正如這個(gè)方法名字一樣進(jìn)行l(wèi)ocale、encoding以及特殊request parameters設(shè)置 try ...{ request = du.wrapRequest(request, servletContext);//對(duì)request進(jìn)行包裝 } catch (IOException e) ...{ String message = "Could not wrap servlet request with Mult; 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);//整個(gè)框架最最核心的方法,下面分析 du.serviceAction(request, response, servletContext, mapping); } finally ...{ afterActionInvocation(request, servletContext, o); ActionContext.setContext(null); } }du.serviceAction(request, response, servletContext, mapping);//這個(gè)方法詢問(wèn)ActionMapper是否需要調(diào)用某個(gè)Action來(lái)處理這個(gè)(request)請(qǐng)求,如果ActionMapper決定需要調(diào)用某個(gè)Action,F(xiàn)ilterDispatcher把請(qǐng)求的處理交給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()); //實(shí)例化Map請(qǐng)求 ,詢問(wèn)ActionMapper是否需要調(diào)用某個(gè)Action來(lái)處理這個(gè)(request)請(qǐng)求 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是通過(guò)兩道getActionName解析出來(lái)的, FilterDispatcher把請(qǐng)求的處理交給ActionProxy,下面是ServletDispatcher的 TODO: request.setAttribute(ServletActionContext.WEBWORK_VALUESTACK_KEY, proxy.getInvocation().getStack()); proxy.execute(); //通過(guò)代理模式執(zhí)行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); } }
4、如果ActionMapper決定需要調(diào)用某個(gè)Action,F(xiàn)ilterDispatcher把請(qǐng)求的處理交給ActionProxy
5、ActionProxy通過(guò)ConfigurationManager詢問(wèn)框架的配置文件,找到需要調(diào)用的Action類 ,這里,我們一般是從struts.xml配置中讀取。
6、ActionProxy創(chuàng)建一個(gè)ActionInvocation的實(shí)例。
7、ActionInvocation實(shí)例使用命名模式來(lái)調(diào)用,在調(diào)用Action的過(guò)程前后,涉及到相關(guān)攔截器(Intercepter)的調(diào)用。
下面我們來(lái)看看ActionInvocation是如何工作的:
ActionInvocation是Xworks 中Action 調(diào)度的核心。而對(duì)Interceptor 的調(diào)度,也正是由ActionInvocation負(fù)責(zé)。ActionInvocation 是一個(gè)接口,而DefaultActionInvocation 則是Webwork 對(duì)ActionInvocation的默認(rèn)實(shí)現(xiàn)。
Interceptor的調(diào)度流程大致如下:
1.ActionInvocation初始化時(shí),根據(jù)配置,加載Action相關(guān)的所有Interceptor。
2. 通過(guò)ActionInvocation.invoke方法調(diào)用Action實(shí)現(xiàn)時(shí),執(zhí)行Interceptor。
Interceptor將很多功能從我們的Action中獨(dú)立出來(lái),大量減少了我們Action的代碼,獨(dú)立出來(lái)的行為具有很好的重用性。XWork、WebWork的許多功能都是有Interceptor實(shí)現(xiàn),可以在配置文件中組裝Action用到的Interceptor,它會(huì)按照你指定的順序,在Action執(zhí)行前后運(yùn)行。
這里,我們簡(jiǎn)單的介紹一下Interceptor
在struts2中自帶了很多攔截器,在struts2-core-2.1.6.jar這個(gè)包下的struts-default.xml中我們可以發(fā)現(xiàn):
<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"/>
對(duì)于sturts2自帶的攔截器,使用起來(lái)就相對(duì)比較方便了,我們只需要在struts.xml的action標(biāo)簽中加入<interceptor-ref name=" logger " />并且struts.xml擴(kuò)展struts-default,就可以使用,
如果是要自定義攔截器,首先需要寫(xiě)一個(gè)攔截器的類:
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中進(jìn)行配置
<!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>
8、一旦Action執(zhí)行完畢,ActionInvocation負(fù)責(zé)根據(jù)struts.xml中的配置找到對(duì)應(yīng)的返回結(jié)果。返回結(jié)果通常是(但不總是,也可能是另外的一個(gè)Action鏈)一個(gè)需要被表示的JSP或者FreeMarker的模版。在表示的過(guò)程中可以使用Struts2 框架中繼承的標(biāo)簽。在這個(gè)過(guò)程中需要涉及到ActionMapper
在上述過(guò)程中所有的對(duì)象(Action,Results,Interceptors,等)都是通過(guò)ObjectFactory來(lái)創(chuàng)建的。
struts2相對(duì)于struts1來(lái)說(shuō)簡(jiǎn)單了很多,并且功能強(qiáng)大了很多,我們可以從幾個(gè)方面來(lái)看:
從體系結(jié)構(gòu)來(lái)看:struts2大量使用攔截器來(lái)出來(lái)請(qǐng)求,從而允許與業(yè)務(wù)邏輯控制器 與 servlet-api分離,避免了侵入性;而struts1.x在action中明顯的侵入了servlet-api.
從線程安全分析:struts2.x是線程安全的,每一個(gè)對(duì)象產(chǎn)生一個(gè)實(shí)例,避免了線程安全問(wèn)題;而struts1.x在action中屬于單線程。
性能方面:struts2.x測(cè)試可以脫離web容器,而struts1.x依賴servlet-api,測(cè)試需要依賴web容器。
請(qǐng)求參數(shù)封裝對(duì)比:struts2.x使用ModelDriven模式,這樣我們 直接 封裝model對(duì)象,無(wú)需要繼承任何struts2的基類,避免了侵入性。
標(biāo)簽的優(yōu)勢(shì):標(biāo)簽庫(kù)幾乎可以完全替代JSTL的標(biāo)簽庫(kù),并且 struts2.x支持強(qiáng)大的ognl表達(dá)式。
當(dāng)然,struts2和struts1相比,在 文件上傳,數(shù)據(jù)校驗(yàn) 等方面也 方便了好多。在這就不詳談了。
一個(gè)比較優(yōu)秀的框架可以幫著我們更高效,穩(wěn)定的開(kāi)發(fā)合格的產(chǎn)品,不過(guò)我們也不要依賴框架,我們只要理解了思想,設(shè)計(jì)模式,我們可以自己擴(kuò)展功能,不然 就要 永遠(yuǎn)讓別人牽著走了!
轉(zhuǎn)自:鏈接
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注