Struts2(二)工作原理
一、概述
1、struts框架本身分为三个部分:核心控制器FilterDispatcher、业务控制器Action和用户实现的企业业务逻辑组件。
2、struts2工作的基本流程:
- 客户端初始化一个指向Servlet容器的请求
- org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter被调用,该过滤器询问ActionMaper这个请求是否需要调用某个Action
- 如果ActionMapper决定需要调用某个Action,StrutsPrepareAndExecuteFilter把请求的处理交给ActionProxy
- ActionProxy通过Configuration Manager询问框架的配置文件,找到需要调用的Action类
- ActionProxy创建一个ActionProxy的实例
- ActionProxy实例使用命名模式来调用
- 一旦Action执行完毕,ActionInvocation负责根据struts.xml中的配置找到对应的返回结果
二、源码分析
下面解析org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter类
public class StrutsPrepareAndExecuteFilter implements StrutsStatics, Filter
{
/*
* prepareOperation对象包含执行请求之前的准备工作
* ExecuteOperations对象包含过滤器的执行操作
*/
protected PrepareOperations prepare;
protected ExecuteOperations execute;
protected List<Pattern> excludedPatterns = null; public void init(FilterConfig filterConfig) throws ServletException
{
//InitOperations类包含一些初始化操作
InitOperations init = new InitOperations();
Dispatcher dispatcher = null;
try
{
//封装filterConfig,其中有个主要方法getInitParameterNames将参数名字以String格式存储在List中
FilterHostConfig config = new FilterHostConfig(filterConfig);
//初始化struts内部日志
init.initLogging(config);
//创建dispatcher ,并初始化
dispatcher = init.initDispatcher(config);
init.initStaticContentLoader(config, dispatcher);
//初始化类属性:prepare 、execute
prepare = new PrepareOperations(dispatcher);
execute = new ExecuteOperations(dispatcher);
this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);
//回调空的postInit方法
postInit(dispatcher, filterConfig);
}
finally
{
if (dispatcher != null) {
dispatcher.cleanUpAfterInit();
}
init.cleanup();
}
}
/**
* Callback for post initialization
*/
protected void postInit(Dispatcher dispatcher, FilterConfig filterConfig)
{
} 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))
{
//过滤器放行
chain.doFilter(request, response);
}
else
{
//设置编码国际化和地点
prepare.setEncodingAndLocale(request, response);
//创建action上下文
//ActionContext是一个线程的本地变量,这意味着不同的action之间不会共享ActionContext,所以也不用考虑线程安全问题
prepare.createActionContext(request, response);
prepare.assignDispatcherToThread();
request = prepare.wrapRequest(request);
ActionMapping mapping = prepare.findActionMapping(request, response, true);
//如果mapping为空,则认为不是调用action,会调用下一个过滤器链,直到获取到mapping才调用action
if (mapping == null)
{
boolean handled = execute.executeStaticResourceRequest(request, response);
if (!handled)
{
chain.doFilter(request, response);
}
}
else
{
//执行action
execute.executeAction(request, response, mapping);
}
}
}
finally
{
prepare.cleanupRequest(request);
}
}
public void destroy() {
prepare.cleanupDispatcher();
}
}
上述源码的第23行:dispatcher = init.initDispatcher(config);
//创建并初始化Dispatcher对象
public Dispatcher initDispatcher( HostConfig filterConfig )
{
Dispatcher dispatcher = createDispatcher(filterConfig);
dispatcher.init();
return dispatcher;
}
创建dispatcher,会读取 filterConfig 中的配置信息,将配置信息解析出来,封装成为一个Map,然后根绝servlet上下文和参数Map构造Dispatcher :
private Dispatcher createDispatcher( HostConfig filterConfig )
{
Map<String, String> params = new HashMap<String, String>();
for(Iterator e = filterConfig.getInitParameterNames(); e.hasNext(); )
{
String name = (String) e.next();
String value = filterConfig.getInitParameter(name);
params.put(name, value);
}
return new Dispatcher(filterConfig.getServletContext(), params);
}
初始化dispatcher过程如下:
public void init()
{
if (configurationManager == null)
{
configurationManager = createConfigurationManager(DefaultBeanSelectionProvider.DEFAULT_BEAN_NAME);
}
//初始化过程中,会加载一些配置文件,例如:default.properties,struts-default.xml,struts-plugin.xml,struts.xml等
try
{
init_FileManager();
init_DefaultProperties(); // [1]
init_TraditionalXmlConfigurations(); // [2]
init_LegacyStrutsProperties(); // [3]
init_CustomConfigurationProviders(); // [5]
init_FilterInitParameters() ; // [6]
init_AliasStandardObjects() ; // [7]
Container container = init_PreloadConfiguration();
container.inject(this);
init_CheckWebLogicWorkaround(container);
if (!dispatcherListeners.isEmpty())
{
for (DispatcherListener l : dispatcherListeners)
{
l.dispatcherInitialized(this);
}
}
errorHandler.init(servletContext);
}
catch (Exception ex)
{
if (LOG.isErrorEnabled())
LOG.error("Dispatcher initialization failed", ex);
throw new StrutsException(ex);
}
}
上述分析的是StrutsPrepareAndExecuteFilter类的init方法,该方法在web容器启动的时候就会被调用,当用户访问某个action时,首先调用StrutsPrepareAndExecuteFilter类的doFilter方法,下面具体分析下这个方法:
- 首先是设置编码格式和地点:
prepare.setEncodingAndLocale(request, response);
- 创建ActionContext,ActionContext(com.opensymphony.xwork.ActionContext)是Action执行时的上下文,上下文可以看作是一个容器(其实我们这里的容器就是一个Map而已),它存放的是Action在执行时需要用到的对象,比如Session、Application、Request、Locale、ValueStack等。
prepare.createActionContext(request, response);
- 分配调度到本地线程调度
prepare.assignDispatcherToThread();
- request进行包装,如果content_type是multipart/form-data类型,则将request包装成MultiPartRequestWrapper对象,否则包装成StrutsRequestWrapper对象
request = prepare.wrapRequest(request);
public HttpServletRequest wrapRequest(HttpServletRequest request) throws IOException
{
// don't wrap more than once
if (request instanceof StrutsRequestWrapper)
{
return request;
}
String content_type = request.getContentType();
if (content_type != null && content_type.contains("multipart/form-data"))
{
MultiPartRequest mpr = getMultiPartRequest();
LocaleProvider provider = getContainer().getInstance(LocaleProvider.class);
request = new MultiPartRequestWrapper(mpr, request, getSaveDir(), provider, disableRequestAttributeValueStackLookup);
}
else
{
request = new StrutsRequestWrapper(request, disableRequestAttributeValueStackLookup);
}
return request;
}
- 然后通过ActionMapper的getMapping()方法得到请求的Action,Action的配置信息存储在ActionMapping对象中,
ActionMapping mapping = prepare.findActionMapping(request, response, true);
我们找到prepare对象的findActionMapping方法:
public ActionMapping findActionMapping(HttpServletRequest request, HttpServletResponse response, boolean forceLookup)
{
//首先从request对象中取mapping对象,看是否存在
ActionMapping mapping = (ActionMapping) request.getAttribute(STRUTS_ACTION_MAPPING_KEY); //struts.actionMapping
//不存在就创建一个
if (mapping == null || forceLookup)
{
try
{
//首先创建ActionMapper对象,通过ActionMapper对象创建mapping对象
mapping = dispatcher.getContainer().getInstance(ActionMapper.class).getMapping(request, dispatcher.getConfigurationManager());
if (mapping != null)
{
request.setAttribute(STRUTS_ACTION_MAPPING_KEY, mapping);
}
} catch (Exception ex) {
dispatcher.sendError(request, response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);
}
}
return mapping;
}
ActionMapper接口的实现类DefaultActionMapper的getMapping()方法的源代码:
public ActionMapping getMapping(HttpServletRequest request, ConfigurationManager configManager)
{
ActionMapping mapping = new ActionMapping();
//获得请求的uri,即请求路径URL中工程名以后的部分,如/HelloWorld.action
String uri = getUri(request);
int indexOfSemicolon = uri.indexOf(";");
uri = (indexOfSemicolon > -1) ? uri.substring(0, indexOfSemicolon) : uri;
//删除扩展名,如.action或者.do
uri = dropExtension(uri, mapping);
if (uri == null)
{
return null;
}
//从uri中分离得到请求的action名、命名空间。
parseNameAndNamespace(uri, mapping, configManager);
//处理特殊的请求参数
handleSpecialParameters(request, mapping);
//如果允许动态方法调用,即形如/HelloWorldAction!getAll.action的请求,分离action名和方法名
return parseActionName(mapping);
}
- 如果mapping为空,则认为不是调用action,会调用下一个过滤器链,直到获取到mapping才调用action
if (mapping == null)
{
boolean handled = execute.executeStaticResourceRequest(request, response);
if (!handled)
{
chain.doFilter(request, response);
}
}
- 如果mapping对象不为空,则会执行action
execute.executeAction(request, response, mapping);
其源码为:
public void serviceAction(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws ServletException
{
//封转上下文环境,主要将requestMap、params、session等Map封装成为一个上下文Map
Map<String, Object> extraContext = createContextMap(request, response, mapping);
// 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();//从mapping对象获取命名空间
String name = mapping.getName(); //获取请求的action名
String method = mapping.getMethod(); //获取请求方法 //根据执行上下文参数,命名空间,名称等创建用户自定义Action的代理对象
ActionProxy proxy = getContainer().getInstance(ActionProxyFactory.class).createActionProxy(
namespace, name, method, extraContext, true, false); request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack()); //如果配置文件中执行的这个action配置了result,就直接转到result
if (mapping.getResult() != null)
{
Result result = mapping.getResult();
result.execute(proxy.getInvocation());
}
else
{
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);
}
}
}
- 最后通过Result完成页面跳转。
Struts2(二)工作原理的更多相关文章
- Struts2的工作原理及工作流程
众所周知,Struts2是个非常优秀的开源框架,我们能用Struts2框架进行开发,同时能 快速搭建好一个Struts2框架,但我们是否能把Struts2框架的工作原理用语言表达清楚,你表达的原理不需 ...
- 菜鸟学Struts2——Struts工作原理
在完成Struts2的HelloWorld后,对Struts2的工作原理进行学习.Struts2框架可以按照模块来划分为Servlet Filters,Struts核心模块,拦截器和用户实现部分,其中 ...
- Struts2的工作原理(图解)详解
Struts2的工作原理 上图来源于Struts2官方站点,是Struts 2 的整体结构. 一个请求在Struts2框架中的处理大概分为以下几个步骤(可查看源码:https://github.com ...
- Struts2 的工作原理
Struts2 的工作原理: 1)client向server发出一个http请求.webserver对请求进行解析,假设在StrutsPrepareAndExecuteFilter的请求映射路径(在w ...
- struts2的工作原理
在学习struts2就必须的了解一下它的工作原理: 首先来看一下这张图 这张工作原理图是官方提供的: 一个请求在Struts2框架中的处理大概分为以下几个步骤 1.客户端初始化一个指向Servlet容 ...
- 第一篇——Struts2的工作原理及HelloWorld简单实现
Struts2工作原理: 一个请求在Struts框架中的处理步骤: 1.客户端初始化一个指向Servlet容器(例如Tomcat)的请求: 2.这个请求经过一系列的过滤器(Filter): 3.接着F ...
- Struts2学习一----------Struts2的工作原理及HelloWorld简单实现
© 版权声明:本文为博主原创文章,转载请注明出处 Struts2工作原理 一个请求在Struts2框架中的处理步骤: 1.客户端初始化一个指向Servlet容器(例如Tomcat)的请求 2.这个请求 ...
- HDSF主要节点解说(二)工作原理
HDFS(Hadoop Distributed File System )Hadoop分布式文件系统. 是依据google发表的论文翻版的.论文为GFS(Google File System)Goog ...
- 分享知识-快乐自己:Struts2框架 工作原理及执行流程图(拦截器的使用)
Struts2 架构图: 1):提交请求 客户端通过 HttpServletRequest 向 Servlet (即Tomcat)提交一个请求. 请求经过一系列的过滤器,例如图中的 ActionCon ...
随机推荐
- mysql数据库性能测试报告
网上有写的好的模板, 直接复链接了: 1. http://blog.csdn.net/mituan1234567/article/details/45247989 2. https://msdn.mi ...
- hibernate向mysql数据库插入中文显示??
- e792. 建立一个包括所有数据的SpinnerListModel
By default, if the user is browsing the values in a SpinnerListModel, the iteration stops when eithe ...
- TPshop下载安装
一. 首先 修改 C:\Windows\System32\drivers\etc\hosts 文件 加一行 127.0.0.1 www.tpshop.com // 这里可以改成你想要的域名 二. 修改 ...
- cocos2d - CCSprite各种动画
转自 ITeye技术网站 // 触摸屏 -(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event { for( UITouc ...
- JSTL时间格式化项目小试
我在之前的博客中虽然详尽的介绍了JSTL在各个载体中的用法,也介绍了它和EL的共同使用的好处,但是只是顺便提了一下JSTL的格式化. 今天在项目中遇到了一个小问题,也就想到这,马上就开始实践了一下,效 ...
- Linux I/O优化 磁盘读写参数设置
关于页面缓存的信息,可以用cat /proc/meminfo 看到.其中的Cached 指用于pagecache的内存大小(diskcache-SwapCache).随着写入缓存页,Dirty 的值会 ...
- Java编程思想学习笔记——类的访问权限
类的访问权限 Java中,访问权限修饰词用于确定库中哪些类对于该库的使用者是可用的. public class Foo{ } 注意点: 每个文件(编译单元)只能有一个public类. public类的 ...
- JS貪食蛇網頁代碼
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <bo ...
- mongodb 关闭服务器
./mongo use admin db.shutdownServer() 啦啦啦