在学习struts2之前,首先我们要明确使用struts2的目的是什么?它能给我们带来什么样的优点?
设计目标
Struts设计的第一目标就是使MVC模式应用于web程序设计。
在这儿MVC模式的优点就不在提了。
技术优势
Struts2有双方面的技术优势,一是全部的Struts2应用程序都是基于client/server HTTP交换协议,The Java Servlet API揭示了Java Servlet仅仅是Java API的一个非常小子集。这样我们能够在业务逻辑部分使用功能强大的Java语言进行程序设计。
二是提供了对MVC的一个清晰的实现,这一实现包括了非常多參与对所以请求进行处理的关键组件,如:拦截器、OGNL表达式语言、堆栈。
由于struts2有这样目标。而且有这种优势,所以。这是我们学习struts2的理由,以下。我们在深入剖析一下struts的工作原理。
工作原理
Suruts2的工作原理能够用以下这张图来描写叙述,以下我们分步骤介绍一下每一步的核心内容
一个请求在Struts2框架中的处理大概分为下面几个步骤
1、client初始化一个指向Servlet容器(比如Tomcat)的请求
2、这个请求经过一系列的过滤器(Filter)(这些过滤器中有一个叫做ActionContextCleanUp的可选过滤器。这个过滤器对于Struts2和其它框架的集成非常有帮助,比如:SiteMesh Plugin)
3、接着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); } }
4、假设ActionMapper决定须要调用某个Action。FilterDispatcher把请求的处理交给ActionProxy
5、ActionProxy通过ConfigurationManager询问框架的配置文件,找到须要调用的Action类 ,这里,我们通常是从struts.xml配置中读取。
6、ActionProxy创建一个ActionInvocation的实例。
7、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中我们能够发现:
对于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中进行配置
/success.jsp
8、一旦Action运行完成,ActionInvocation负责依据struts.xml中的配置找到相应的返回结果。返回结果一般是(但不总是,也可能是另外的一个Action链)一个须要被表示的JSP或者FreeMarker的模版。在表示的过程中能够使用Struts2 框架中继承的标签。在这个过程中须要涉及到ActionMapper
在上述过程中全部的对象(Action,Results。Interceptors。等)都是通过ObjectFactory来创建的。
Struts2和struts1的比較
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相比。在 文件上传。数据校验 等方面也 方便了好多。在这就不详谈了。
一个比較优秀的框架能够帮着我们更高效。稳定的开发合格的产品。只是我们也不要依赖框架,我们仅仅要理解了思想,设计模式。我们能够自己扩展功能。不然 就要 永远让别人牵着走了。