读了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的显示方式)
分享到:
相关推荐
讲述Struts2的工作原理。struts2源代码分析(个人觉得非常经典),讲解全面且易懂。
通过深入阅读"struts2源代码分析(个人觉得非常经典).doc"、"struts2源代码分析.docx"和解压后的"struts2源代码.rar",你可以获得Struts2框架的全面理解,从而更好地利用这个框架进行Web应用的开发和维护。...
struts2源代码分析(个人觉得非常经典).pdf
在分析"struts源代码源代码源代码"这个标题时,我们可以推断出讨论的主题是关于Struts框架的源码。Struts 2是其最新版本,基于Action和拦截器的模型,提供了灵活的控制流和强大的插件架构。源代码的学习可以帮助我们...
Struts2.0是Apache软件基金会的...通过深入学习和分析“SSH2Project”这个压缩包中的源代码,开发者不仅可以掌握Struts2.0的运行机制,还能提升解决实际问题的能力,为构建高效、可维护的Java Web应用打下坚实的基础。
Struts2源代码分析: 1. **核心组件**: - **Action**:它是业务逻辑的载体,通常继承自`com.opensymphony.xwork2.ActionSupport`或自定义Action接口。 - **Interceptor**:拦截器是Struts2的重要特性,它允许在...
通过查看和分析源代码,你可以理解Struts2的拦截器机制、Action调度、结果渲染等核心概念,同时也能了解到如何在实际项目中配置和使用Struts2。对于想要提升Java Web开发技能,特别是对MVC框架感兴趣的开发者来说,...
在"struts2教程源代码"中,你可以找到一系列用于学习和实践Struts2框架的实例。这些源代码是针对初学者设计的,旨在帮助理解如何在实际应用中运用Struts2的核心概念和特性。"strut2课程源代码第一天及说明"可能包含...
总之,分析和学习Struts2.0.11源代码对于提升Java Web开发技能、理解MVC架构以及优化应用程序性能都具有极大的价值。如果你希望深入Web开发,那么掌握Struts2框架的内部运作无疑是一个重要的里程碑。
JavaEE源代码与Struts2源代码是JavaWeb开发中的重要组成部分,对于深入理解Web应用程序的构建和运行机制至关重要。JavaEE(Java Platform, Enterprise Edition)是Java平台的一个版本,专为开发和部署企业级应用而...
源代码分析可以帮助我们深入理解其设计理念、工作原理以及内部机制。 在Struts1的源代码中,`org`目录通常是框架的核心组件包,包含了许多关键类和接口。以下是一些重要的知识点: 1. **ActionServlet**:这是...