菜鸟学Struts2——Struts工作原理

时间:2022-02-19 01:07:10

  在完成Struts2的HelloWorld后,对Struts2的工作原理进行学习。Struts2框架可以按照模块来划分为Servlet Filters,Struts核心模块,拦截器和用户实现部分,其中需要用户实现的部分只有三个,那就是struts.xml,Action,Template(JSP),如下图:

菜鸟学Struts2——Struts工作原理

2.3.31中的org.apache.struts2.dispatcher.ActionContextCleanUp已经被标记为@Deprecated Since Struts 2.1.3,2.1.3之后FilterDispatcher已经改为org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter,2.5.0之后又被移到了父包中,即不在ng包下面,直接在父包中org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter

(1) 在struts2.3.31中FilterDispatcher就是StrutsPrepareAndExecuteFilter,Struts的过滤器根据<url-pattern>/*</url-pattern>拦截请求,doFilter(org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter)核心代码如下:

 public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
try {
if (excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {
// 如果常量struts.action.excludePattern指定了不被拦截的Url这里直接放行
chain.doFilter(request, response);
} else {
prepare.setEncodingAndLocale(request, response);
prepare.createActionContext(request, response);
prepare.assignDispatcherToThread();
request = prepare.wrapRequest(request);
// 通过ActionMapper获取ActionMapping
ActionMapping mapping = prepare.findActionMapping(request, response, true);
if (mapping == null) {
boolean handled = execute.executeStaticResourceRequest(request, response);
if (!handled) {
chain.doFilter(request, response);
}
} else {
// 调用dispatcher.serviceAction()执行Action
execute.executeAction(request, response, mapping);
}
}
} finally {
prepare.cleanupRequest(request);
}
}

(2)StrutsPrepareAndExecuteFilter通过Dispatcher(org.apache.struts2.dispatcher.Dispatcher)的serviceAction()方法获取ActionProxy去执行Action,核心代码如下:

 public void serviceAction(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping)
throws ServletException {
Map<String, Object> extraContext = createContextMap(request, response, mapping);
// 获取值栈OgnlValueStack implements ValueStack
// 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();
// 获取Action代理执行Action
ActionProxy proxy = 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 {
// Action代理执行Action
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) {
logConfigurationException(request, e);
sendError(request, response, HttpServletResponse.SC_NOT_FOUND, e);
} catch (Exception e) {
if (handleException || devMode) {
sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
} else {
throw new ServletException(e);
}
} finally {
UtilTimerStack.pop(timerKey);
}
}

(3)Dispatcher通过ActionProxy的execute()方法执行Action,ActionProxy默认的实现是com.opensymphony.xwork2.DefaultActionProxy,ActionProxy执行ActionInvocation.invoke()代理执行Action,核心代码如下:

 public String execute() throws Exception {
ActionContext nestedContext = ActionContext.getContext();
ActionContext.setContext(invocation.getInvocationContext()); String retCode = null; String profileKey = "execute: ";
try {
UtilTimerStack.push(profileKey);
// invoke代理执行Action
retCode = invocation.invoke();
} finally {
if (cleanupContext) {
ActionContext.setContext(nestedContext);
}
UtilTimerStack.pop(profileKey);
}
return retCode;
}

(4)ActionInvocation会执行一系列的Struts的拦截器如上图,而拦截器就只有一个参数,那就是ActionInvocation,在拦截器里面加入一些其他逻辑然后又调用ActionInvocation.invoke()又回到ActionInvocation.invoke(),这样循环直到interceptors.hasNext()没有拦截器为止才执行Action,即调用invokeActionOnly()执行Action,Action执行之后会接着执行executeResult(),上图的Result在Action执行之后,并将executed标记为true,这样result就生成了,当执行拦截器调用ActionInvocation.invoke()之后的代码完成就不会再对result造成任何影响了,核心代码如下:

 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 = interceptors.next();
String interceptorMsg = "interceptor: " + interceptor.getName();
UtilTimerStack.push(interceptorMsg);
try {
// 执行拦截器,拦截器中执行invocation.invoke()回到这里调用下一个拦截器
resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
// 所有拦截的执行invocation.invoke()之后的代码完成,此时下面的executed已经被标记成true不会再次执行
}
finally {
UtilTimerStack.pop(interceptorMsg);
}
} else {
// 所有拦截器invocation.invoke()之前的代码执行完后执行Action
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) {
LOG.trace("Executing PreResultListeners for result [#0]", result); for (Object preResultListener : preResultListeners) {
PreResultListener listener = (PreResultListener) preResultListener; String _profileKey = "preResultListener: ";
try {
UtilTimerStack.push(_profileKey);
listener.beforeResult(this, resultCode);
}
finally {
UtilTimerStack.pop(_profileKey);
}
}
}
// Action执行完成,执行Result
// now execute the result, if we're supposed to
if (proxy.getExecuteResult()) {
executeResult();
}
// 并标记executed为true
executed = true;
}
// 返回ResultCode
return resultCode;
}
finally {
UtilTimerStack.pop(profileKey);
}
}

下面是Struts2配置的默认拦截器:

菜鸟学Struts2——Struts工作原理

至此,Struts2一次请求就完成了。

未完,待续。