读了struts2 2.3.1部分源代码,想和大家分享下心得,看看struts2内部做了哪些事情,并从中学习此类架构的设计思想
1) StrutsPrepareAndExecuteFilter
struts2以后web.xml的配置已经由配置servlet变成配置filter了
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); //创建当前线程的ActionContext
prepare.assignDispatcherToThread(); //将dispatcher赋给当前线程
if ( excludedPatterns != null && prepare.isUrlExcluded(request, excludedPatterns)) {
chain.doFilter(request, response); //如果该URL被exclude掉,继续chaining
} else {
request = prepare.wrapRequest(request); //包装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); // hit! 将请求交给dispatcher,触发其serviceAction方法(dispatcher.serviceAction(request, response, servletContext, mapping);)
}
}
} finally {
prepare.cleanupRequest(request);
}
}
2) Dispatcher
struts中的核心类,构造actionproxy以及actioninvocation,加载action类并调用其方法
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) {
//将值栈put进extraContext
extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack));
}
String timerKey = "Handling request from Dispatcher";
try {
UtilTimerStack.push(timerKey);
String namespace = mapping.getNamespace(); // action名空间
String name = mapping.getName(); //action名称
String method = mapping.getMethod(); //action方法
Configuration config = configurationManager.getConfiguration();
ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(
namespace, name, method, extraContext, true, false); //创建actionproxy以及actioninvocation
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(); //hit! 执行对应action的方法(默认proxy实现是StrutsActionProxy)
}
// 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 {
if (LOG.isWarnEnabled()) {
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);
}
}
3)StrutsActionProxy
struts中action的代理类
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(); // 调用actioninvocation(默认实现是DefaultActionInvocation)
} finally {
if (cleanupContext)
ActionContext.setContext(previous);
}
}
4) DefaultActionInvocation
可以理解为承载action拦截器和action实例的容器,负责调用拦截器以及action的方法并将结果拼装起来
public String invoke() throws Exception {
String profileKey = "invoke: ";
try {
UtilTimerStack.push(profileKey);
if (executed) { //判断当前的状态
throw new IllegalStateException("Action has already executed");
}
//loop拦截器并执行
if (interceptors.hasNext()) {
final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();
String interceptorMsg = "interceptor: " + interceptor.getName();
UtilTimerStack.push(interceptorMsg);
try {
//每个拦截器的实现最后都会调用一次invocation.invoke();从而实现了链式调用(chaining)
resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
}
finally {
UtilTimerStack.pop(interceptorMsg);
}
} else {
resultCode = invokeActionOnly(); //chaining的最后一步,调用action的方法
}
// 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);
}
}
private void executeResult() throws Exception {
result = createResult(); //根据配置创建result,result种类很多, actionchainresult、httpheaderresult、freemarkerresult等
String timerKey = "executeResult: " + getResultCode();
try {
UtilTimerStack.push(timerKey);
if (result != null) {
//根据结果类型,将数据以及view拼装起来,返回至前台
result.execute(this);
} else if (resultCode != null && !Action.NONE.equals(resultCode)) {
throw new ConfigurationException("No result defined for action " + getAction().getClass().getName()
+ " and result " + getResultCode(), proxy.getConfig());
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("No result returned for action " + getAction().getClass().getName() + " at " + proxy.getConfig().getLocation());
}
}
} finally {
UtilTimerStack.pop(timerKey);
}
}
小节
良好的框架可以运用语言的特性以及设计模式来实现解耦
struts2非常好用的两个功能可以在上述代码找到答案(拦截器、扩展view的显示方式)