Struts2的整体流程

来源:互联网 发布:德驰跟锐驰的差别 知乎 编辑:程序博客网 时间:2024/04/30 23:45
Struts2的整体流程

 转自:http://blog.163.com/hzd_love/blog/static/13199988120107289624669/

Struts 2框架本身大致可以分为3个部分:核心控制器FilterDispatcher、业务控制器Action和用户实现的企业业务逻辑组件。
核心控制器FilterDispatcher
核心控制器FilterDispatcher是Struts 2框架的基础,包含了框架内部的控制流程和处理机制。业务控制器Action和业务逻辑组件是需要用户来自己实现的。用户在开发Action和业务逻辑组件的同时,还需要编写相关的配置文件,供核心控制器FilterDispatcher来使用。
Struts 2的工作流程相对于Struts 1要简单,与WebWork框架基本相同,所以说Struts 2是WebWork的升级版本。Struts 2框架按照模块来划分,可以分为Servlet Filters、Struts核心模块、拦截器和用户实现部分。Struts 2框架结构图如图1所示。

图1 Struts 2框架结构图
一个请求在Struts 2框架中的处理大概分为以下几个步骤。
客户端提交一个(HttpServletRequest)请求,如上文在浏览器中输入
http://localhost: 8080/bookcode/ch2/Reg.action就是提交一个(HttpServletRequest)请求。
请求被提交到一系列(主要是3层)的过滤器(Filter),如(ActionContextCleanUp、其他过滤器(SiteMesh等)、 FilterDispatcher)。注意:这里是有顺序的,先ActionContext CleanUp,再其他过滤器(Othter Filters、SiteMesh等),最后到FilterDispatcher。
FilterDispatcher是控制器的核心,就是MVC的Struts 2实现中控制层(Controller)的核心。
FilterDispatcher询问ActionMapper是否需要调用某个Action来处理这个(HttpServlet Request)请求,如果ActionMapper决定需要调用某个Action,FilterDispatcher则把请求的处理交给ActionProxy。
ActionProxy通过Configuration Manager(struts.xml)询问框架的配置文件,找到需要调用的Action类。例如,用户注册示例将找到UserReg类。
ActionProxy创建一个ActionInvocation实例,同时ActionInvocation通过代理模式调用Action。但在调用之前,ActionInvocation会根据配置加载Action相关的所有Interceptor(拦截器)。
一旦Action执行完毕,ActionInvocation负责根据struts.xml中的配置找到对应的返回结果result。
Struts 2的核心控制器是FilterDispatcher,有3个重要的方法:destroy()、doFilter()和Init(),可以在Struts 2的下载文件夹中找到源代码,如代码1所示。
代码1 核心控制器FilterDispatcher
public class FilterDispatcher implements StrutsStatics, Filter {
/**
* 定义一个Log实例
*/
private static final Log LOG = LogFactory.getLog(FilterDispatcher.class);
… ...
/**
* 存放属性文件中的.STRUTS_I18N_ENCODING值
*/
private static String encoding;
/**
* 定义ActionMapper实例
*/
private static ActionMapper actionMapper;
/**
* 定义FilterConfig实例
*/
private FilterConfig filterConfig;
protected Dispatcher dispatcher;
/**
* 创建一个默认的dispatcher,初始化filter
* 设置默认的packages *
*/
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
dispatcher = createDispatcher(filterConfig);
dispatcher.init();
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);
}
//销毁filter方法
public void destroy() {
if (dispatcher == null) {
LOG.warn("something is seriously wrong, Dispatcher is not initialized (null) ");
} else {
dispatcher.cleanup();
}
}
/**
* 处理一个Action或者资源请求
*

* filter尝试将请求同action mapping相匹配
* 如果找到,将执行dispatcher的serviceAction方法
* 如果Action处理失败, doFilter将建立一个异常
*

* 如果请求静态资源
* 资源将被直接复制给 response
*

* 如果找不到匹配Action 或者静态资源,则直接跳出
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) {
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 {
//为一个普通的request, 则通过
chain.doFilter(request, response);
}
return;
}
/**
*这个方法询问ActionMapper是否需要调用某个Action来处理这个(request)请求,
*如果ActionMapper决定需要调用某个Action,
*FilterDispatcher则把请求的处理交给ActionProxy
dispatcher.serviceAction(request, response, servletContext, mapping);
} finally {
try {
ActionContextCleanUp.cleanUp(req);
} finally {
UtilTimerStack.pop(timerKey);
}
}
}
… …
}
在doFilter()方法中,将调用dispatcher.serviceAction,该方法如果找到相应的Action,将把用户请求交给ActionProxy。serviceAction()代码在Dispatcher.java中,如代码2所示。
代码2 Dispatcher类
public class Dispatcher {
...
/**
* 为mapping加载类,并调用相应的方法或者直接返回result
*

* 根据用户请求的参数,建立Action上下文
* 根据指定的Action’名称和包空间名称,加载一个Action代理ActionProxy
* 然后Action的相应方法将被执行,
*/
public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context, ActionMapping mapping)throws ServletException {
Map extraContext = createContextMap(request, response, mapping, context);
//如果存在一个值栈,则建立一个新的并复制以备Action使用
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";
try {
UtilTimerStack.push(timerKey);
String namespace = mapping.getNamespace();
String name = mapping.getName();
String method = mapping.getMethod();
Configuration config = configurationManager.getConfiguration();
//FilterDispatcher把请求的处理交给ActionProxy
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());
//ActionMapping 直接返回一个result
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);
}
}
从上面代码中可以看出来,Struts 2用于处理用户请求的Action实例,并不是用户实现的业务控制器,而是Action代理。关于Action代理相关内容,读者可以参考拦截器章节的介绍。
原创粉丝点击