- 浏览: 15724 次
文章分类
最新评论
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以后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源码解析STRUTS2源码解析STRUTS2源码解析STRUTS2源码解析STRUTS2源码解析STRUTS2源码解析STRUTS2源码解析STRUTS2源码解析STRUTS2源码解析STRUTS2源码解析STRUTS2源码解析STRUTS2源码解析STRUTS2源码解析...
在"struts2源码解析.pdf"文档中,主要探讨了以下几个关键组件及其功能: 1. **ActionContext**: - `ActionContext`是Struts2的核心上下文,它存储了与当前Action执行相关的所有信息,如请求参数、session数据等。...
配置相关的类位于`org.apache.struts2.config`包,这里包含读取和解析XML及properties文件的类。`org.apache.struts2.interceptor`包定义了内置的拦截器,例如身份验证、异常处理等,开发者可以根据需要自定义拦截器...
struts2源码详细解析51CTO下载-struts2源代码分析(个人觉得非常经典)
### Struts2源码解析及工作原理 #### Struts2简介 Struts2是一个流行的Java Web应用程序框架,它继承和发展了Struts1.x的一些特性,同时又采用了WebWork框架的核心技术,使得Struts2在设计理念和技术实现上都有了...
本文将深入解析Struts1的源码,以帮助理解其内部工作原理。 首先,我们从ActionServlet的生命周期开始。ActionServlet是Struts1的核心组件,它的生命周期分为初始化、拦截请求和销毁三个阶段。在初始化阶段,`init...
Struts2 源码分析 Struts2 是一个基于MVC 模式的Web 应用程序框架,它的源码分析可以帮助我们更好地理解框架的内部机制和工作流程。下面是Struts2 源码分析的相关知识点: 1. Struts2 架构图 Struts2 的架构图...
总的来说,这篇“Struts2源码解读”的博文应该是对Struts2核心机制进行了详细的解析,包括Action、Interceptor、Result等关键组件的工作原理,以及整个请求处理流程。通过学习这些内容,开发者可以深化对Struts2的...
4. `ConfigurationProvider`和`Configuration`:`ConfigurationProvider`解析Struts2的配置文件,如`struts.xml`。默认实现`XmlConfigurationProvider`和`StrutsXmlConfigurationProvider`负责读取和解析这些配置。 ...
Struts2是一个基于MVC设计模式的Web应用框架,它本质上相当于一个servlet,在MVC设计模式中,Struts2作为控制器(Controller)来建立模型与视图的数据交互。Struts 2是Struts的下一代产品. 文档中对于代码进行重要部分...
这份"struts2源码解析[归纳].pdf"文档显然深入探讨了Struts2的核心组件和工作原理。以下是对其中提到的关键概念的详细解释: 1. **ActionContext**: ActionContext是Struts2中一个非常重要的类,它封装了当前请求...
最新版的Struts2源码可以从GitHub的Apache官方仓库获取,这为我们提供了深入理解其内部工作原理和定制功能提供了可能。 Struts2的核心特性包括: 1. **Action与结果**:在Struts2中,业务逻辑处理主要由Action类...
在`Dispatcher`的初始化过程中,它会读取`web.xml`或其他配置文件,解析Struts2的配置信息,如Action、结果类型、拦截器等。这些配置信息被加载到内存中的容器中,供后续请求处理时使用。`Dispatcher`还负责初始化...
将Struts 2源码导入Eclipse工程,对于学习和理解框架的工作原理以及进行自定义开发具有重要意义。 首先,导入Struts 2源码到Eclipse需要遵循以下步骤: 1. 下载Struts 2的源码包,通常可以从Apache官方网站获取...
本资料包包含的是《Struts2深入详解》一书的源码分析,涵盖了从第一章到第五章的内容,并附带了相关的jar包,方便读者结合理论与实践进行学习。 首先,让我们从第一章开始,Struts2的基础知识。这一章通常会介绍...
2. **Eclipse关联Struts2源码** 在Eclipse中关联Struts2.1.8源码,可以帮助开发者更好地理解和调试代码。步骤包括: - 下载Struts2.1.8的源码包。 - 在Eclipse中,右键点击项目,选择"Build Path" -> "Configure ...
在深入研究Struts2源码时,我们可以关注以下几个关键部分: 1. **org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter**:这是Struts2的核心过滤器,它初始化并调用Struts2的生命周期。 2. **...
通过对Struts2源码的深入研究,开发者可以更好地理解其内部工作原理,从而优化应用性能,解决实际问题,以及设计出更符合框架精神的代码结构。同时,这也为面试中展示自己的技术深度和问题解决能力提供了有力的支持...
Struts2的源码解析文档通常会涵盖以下几个核心部分: 1. **FilterDispatcher**:这是Struts2框架的入口点,负责拦截HTTP请求并根据配置将请求转发到相应的Action。源码分析会解释其如何处理请求、如何查找Action及...
通过对`org`目录下源码的分析,我们可以看到Struts 2的内部工作机制,包括Action的执行流程、拦截器链的构建、配置解析的过程等,这有助于我们更好地优化和调试基于Struts 2的应用程序。同时,对于想要为Struts 2...