官方的流程图:
客户端对tomcat服务器发出请求,将请求封装成HttpRequest对象,并进行预处理操作(如设置编码等);
通过web.xml文件 找到struts2的前端控制器StrutsPrepareAndExcuteFilter,并调用doFilter()方法。
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
try {
prepare.setEncodingAndLocale(request, response);
prepare.createActionContext(request, response);
prepare.assignDispatcherToThread();
if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {
chain.doFilter(request, response);
} else {
request = prepare.wrapRequest(request);
ActionMapping mapping = prepare.findActionMapping(request, response, true);
if (mapping == null) {
boolean handled = execute.executeStaticResourceRequest(request, response);
if (!handled) {
chain.doFilter(request, response);
}
} else {
execute.executeAction(request, response, mapping);
}
}
} finally {
prepare.cleanupRequest(request);
}
}
doFilter中:
1、设置编码;
2、创建ActionContext,创建ValueStack对象。
3、对请求进行重新封装,根据请求内容的类型不同,返回不同的对象:
如果为multipart/form-data类型,则返回MultiPartRequestWrapper类型的对象,否则返回StrutsRequestWrapper类型的对象,MultiPartRequestWrapper是StrutsRequestWrapper的子类,而这两个类都是HttpServletRequest接口的实现。
4、根据请求request获取actionMapping对象
ActionMapping mapping = prepare.findActionMapping(request, response, true);
如果mapping为null,说明请求的不是Action,会调用execute.executeStaticResourceRequest(request, response);方法,请求静态资源。
如果mapping不为null,调用execute.executeAction(request, response, mapping),在这个方法中又调用
dispatcher.serviceAction(request, response, servletContext, mapping);方法。
public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,
ActionMapping mapping) throws ServletException {
Map<String, Object> extraContext = createContextMap(request, response, mapping, context);
// If there was a previous value stack, then create a new copy and pass it in to be used by the new Action
ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
boolean nullStack = stack == null;
if (nullStack) {
ActionContext ctx = ActionContext.getContext();
if (ctx != null) {
stack = ctx.getValueStack();
}
}
if (stack != null) {
extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.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();
ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(
namespace, name, method, extraContext, true, false);
request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack());
// if the ActionMapping says to go straight to a result, do it!
if (mapping.getResult() != null) {
Result result = mapping.getResult();
result.execute(proxy.getInvocation());
} else {
proxy.execute();
}
// If there was a previous value stack then set it back onto the request
if (!nullStack) {
request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);
}
} catch (ConfigurationException e) {
// WW-2874 Only log error if in devMode
if(devMode) {
String reqStr = request.getRequestURI();
if (request.getQueryString() != null) {
reqStr = reqStr + "?" + request.getQueryString();
}
LOG.error("Could not find action or result\n" + reqStr, e);
}
else {
LOG.warn("Could not find action or result", e);
}
sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e);
} catch (Exception e) {
sendError(request, response, context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
} finally {
UtilTimerStack.pop(timerKey);
}
}
在这个serviceAction方法中,
1、将相关对象信息封装为Map(如:HttpServletRequest、Http parameters、HttpServletResponse、HttpSession、ServletContext、ActionMapping等对象信息),存入到执行上下文Map中,返回执行上下文Map对象extraMap;
2、获取ValueStack对象,并放入map中
3、获取mapping对象中存储的action命名空间、name属性、method属性等信息;
4、加载并解析Struts2配置文件,如果没有人为配置,默认按顺序加载struts-default.xml、struts-plugin.xml、struts.xml,将action配置、result配置、interceptor配置,解析并存入至config对象中,返回文件配置对象config;
5、 根据执行上下文Map、action命名空间、name属性、method属性等创建ActionProxy对象;
createActionProxy()方法中:
5.1、创建invacation:ActionInvocation inv= new DefaultActionInvocation(extraContext, true);
5.2、创建proxy:DefaultActionProxy proxy = new DefaultActionProxy(inv, namespace, actionName, methodName, executeResult, cleanupContext);
5.3、接着,proxy.prepare();方法中
5.4、初始化action:invocation.init(this);方法中
使用反射创建action,并压入值栈栈顶,准备拦截器集合。
接着:
6、 执行ActionProxy对象的proxy.execute()方法,并转向结果;
public String execute() throws Exception {
ActionContext previous = ActionContext.getContext();
ActionContext.setContext(invocation.getInvocationContext());
try {
// This is for the new API:
// return RequestContextImpl.callInContext(invocation, new Callable<String>() {
// public String call() throws Exception {
// return invocation.invoke();
// }
// });
return invocation.invoke();
} finally {
if (cleanupContext)
ActionContext.setContext(previous);
}
}
该方法调用了invocation.invoke()方法。
public String invoke() throws Exception {
String profileKey = "invoke: ";
try {
UtilTimerStack.push(profileKey);
if (executed) {
throw new IllegalStateException("Action has already executed");
}
if (interceptors.hasNext()) {
final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();
String interceptorMsg = "interceptor: " + interceptor.getName();
UtilTimerStack.push(interceptorMsg);
try {
resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
}
finally {
UtilTimerStack.pop(interceptorMsg);
}
} else {
resultCode = invokeActionOnly();
}
// this is needed because the result will be executed, then control will return to the Interceptor, which will
// return above and flow through again
if (!executed) {
if (preResultListeners != null) {
for (Object preResultListener : preResultListeners) {
PreResultListener listener = (PreResultListener) preResultListener;
String _profileKey = "preResultListener: ";
try {
UtilTimerStack.push(_profileKey);
listener.beforeResult(this, resultCode);
}
finally {
UtilTimerStack.pop(_profileKey);
}
}
}
// now execute the result, if we're supposed to
if (proxy.getExecuteResult()) {
executeResult();
}
executed = true;
}
return resultCode;
}
finally {
UtilTimerStack.pop(profileKey);
}
}
该方法实现了对 拦截器的递归调用,拦截器的实现采用了责任链模式,所有拦截器必须实现接口Interceptor的intercept(ActionInvocation invocation)方法,该方法的参数为ActionInvocation,所以在方法最后调用invocation.invoke()方法就实现了拦截器的递归调用。
拦截器调用一遍,直到最后一个invoke()方法,拦截器列表中没有未执行的拦截器,这时,会执行action相应的方法,并得到resultCode,接着,在返回Result之前,会执行PreResultListener的beforeResult()方法 ,最后执行结果,找到resultCode对应的结果类型,生成result对象,根据result的信息,或者生成相应response,或者根据结果类型继续执行。最后,对于本次Action请求将相应的执行状态标志位设置,返回resultCode。
这时最后一个拦截器中的invoke()方法得到返回值,由于action和result相应的执行状态标志已经设置为执行过,所以通过上级拦截器中的invoke()方法将对下级拦截器的intercept()方法后的代码进行判断,action、result只执行一遍。然后拦截器由后往前返回,到此整个请求处理流程结束。
回顾整个流程:
a) 客户端初始化一个指向Servlet容器的请求;
b) 根据Web.xml配置,请求首先经过核心过滤器StrutsPrepareAndExcuteFilter,执行doFilter方法,在该方法中,这只编码,创建valuestack对象,询问ActionMapper来决定这个请求是否需要调用某个Action;如果ActionMapper决定需要调用某个Action,则ActionMapper会返回一个ActionMapping实例(存储Action的配置信息),调用executeAction()方法,
c)调用dispatcher.serviceAction()方法,创建ActionProxy(Action代理)对象,将请求交给代理对象继续处理;
d) ActionProxy对象根据ActionMapping和Configuration Manager询问框架的配置文件,找到需要调用的Action类;
e) ActionProxy对象创建时,会同时创建一个ActionInvocation的实例,并对action进行初始化,压入值栈栈顶;
f) 执行proxy.execute()方法,调用invocation.invoke()方法
f) ActionInvocation的invoke()方法中,在调用Action的过程前后,涉及到相关拦截器(Intercepter)的调用;
g) 一旦Action执行完毕,ActionInvocation实例负责根据struts.xml中的配置创建并返回Result。Result通常是一个需要被表示的JSP或者FreeMarker的模版,也可能是另外的一个Action链;
h) 如果要在返回Result之前做些什么,可以实现PreResultListener接口,PreResultListener可以在Interceptor中实现,也可以在Action中实现;
i) 根据Result对象信息,生成用户响应信息response,在生成响应过程中可以使用Struts2 框架中继承的标签,在此过程中仍会再次涉及到ActionMapper;
本文参考http://mktao.blog.51cto.com/5866429/978913