struts2代码分析

来源:百度文库 编辑:神马文学网 时间:2024/04/29 16:04:37
分类:默认栏目
据说struts2是根据webwork的哲学修改过来的。下了struts2的代码看了看,果然跟webwork如出一辙。不过struts2貌似更简洁一些。
webwork的精华在于和http解耦,基于接口编程,以及利用IOC的解耦设计。拦截器是它非常漂亮的思想,当然实现也非常的漂亮。
下面是代码
public void serviceAction(HttpServletRequest request,
HttpServletResponse response, ServletContext context,
ActionMapping mapping) throws ServletException {
Map 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);
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();
String id = request
.getParameter(XWorkContinuationConfig.CONTINUE_PARAM);
if (id != null) {
// remove the continue key from the params - we don‘t want to
// bother setting
// on the value stack since we know it won‘t work. Besides, this
// breaks devMode!
Map params = (Map) extraContext.get(ActionContext.PARAMETERS);
params.remove(XWorkContinuationConfig.CONTINUE_PARAM);
// and now put the key in the context to be picked up later by
// XWork
extraContext.put(XWorkContinuationConfig.CONTINUE_KEY, id);
}
// 代理,实现了接口到实现的转换。
ActionProxy proxy = ActionProxyFactory.getFactory()
.createActionProxy(configurationManager.getConfiguration(),
namespace, name, extraContext, true, false);
proxy.setMethod(method);
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();
// 执行action
result.execute(proxy.getInvocation());
} else {
proxy.execute();
}
// If there was a previous value stack then set it back onto the
// request
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) {
LOG.error("Could not execute action", e);
sendError(request, response, context,
HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
} finally {
UtilTimerStack.pop(timerKey);
}
}