- 浏览: 220392 次
- 性别:
- 来自: 苏州
文章分类
最新评论
-
狂盗一枝梅:
先 收 藏 了再说,struts2太复杂了
Struts2源码阅读(六)_ActionProxy&ActionInvocation -
jingwangfei:
Struts2源码阅读(二)_ActionContext及CleanUP Filter -
liguanqun811:
nbboy 写道"Dispatcher等都是通过Th ...
Struts2源码阅读(三)_Dispatcher&ConfigurationProvider -
nbboy:
"Dispatcher等都是通过ThreadLoca ...
Struts2源码阅读(三)_Dispatcher&ConfigurationProvider -
左脚穿右鞋:
请问我想在tomcat上做应该怎么配置?
JMS应用示例教程
Dispatcher已经在之前讲过,这就好办了。FilterDispatcher是Struts2的核心控制器,首先看一下init()方法。
public void init(FilterConfig filterConfig) throws ServletException { try { this.filterConfig = filterConfig; initLogging(); //创建dispatcher,前面都已经讲过啰 dispatcher = createDispatcher(filterConfig); dispatcher.init(); //注入将FilterDispatcher中的变量通过container注入,如下面的staticResourceLoader dispatcher.getContainer().inject(this); //StaticContentLoader在BeanSelectionProvider中已经被注入了依赖关系:DefaultStaticContentLoader //可以在struts-default.xml中的<bean>可以找到 staticResourceLoader.setHostConfig(new FilterHostConfig(filterConfig)); } finally { ActionContext.setContext(null); } }
//下面来看DefaultStaticContentLoader的setHostConfig public void setHostConfig(HostConfig filterConfig) { //读取初始参数pakages,调用parse(),解析成类似/org/apache/struts2/static,/template的数组 String param = filterConfig.getInitParameter("packages"); //"org.apache.struts2.static template org.apache.struts2.interceptor.debugging static" String packages = getAdditionalPackages(); if (param != null) { packages = param + " " + packages; } this.pathPrefixes = parse(packages); initLogging(filterConfig); }
现在回去doFilter的方法,每当有一个Request,都会调用这些Filters的doFilter方法
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; ServletContext servletContext = getServletContext(); String timerKey = "FilterDispatcher_doFilter: "; try { // FIXME: this should be refactored better to not duplicate work with the action invocation //先看看ValueStackFactory所注入的实现类OgnlValueStackFactory //new OgnlValueStack ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack(); ActionContext ctx = new ActionContext(stack.getContext()); ActionContext.setContext(ctx); UtilTimerStack.push(timerKey); //如果是multipart/form-data就用MultiPartRequestWrapper进行包装 //MultiPartRequestWrapper是StrutsRequestWrapper的子类,两者都是HttpServletRequest实现 //此时在MultiPartRequestWrapper中就会把Files给解析出来,用于文件上传 //所有request都会StrutsRequestWrapper进行包装,StrutsRequestWrapper是可以访问ValueStack //下面是参见Dispatcher的wrapRequest // String content_type = request.getContentType(); //if(content_type!= null&&content_type.indexOf("multipart/form-data")!=-1){ //MultiPartRequest multi =getContainer().getInstance(MultiPartRequest.class); //request =new MultiPartRequestWrapper(multi,request,getSaveDir(servletContext)); //} else { // request = new StrutsRequestWrapper(request); // } request = prepareDispatcherAndWrapRequest(request, response); ActionMapping mapping; try { //根据url取得对应的Action的配置信息 //看一下注入的DefaultActionMapper的getMapping()方法.Action的配置信息存储在 ActionMapping对象中 mapping = actionMapper.getMapping(request, dispatcher.getConfigurationManager()); } catch (Exception ex) { log.error("error getting ActionMapping", ex); dispatcher.sendError(request, response, servletContext, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex); return; } //如果找不到对应的action配置,则直接返回。比如你输入***.jsp等等 //这儿有个例外,就是如果path是以“/struts”开头,则到初始参数packages配置的包路径去查找对应的静态资源并输出到页面流中,当然.class文件除外。如果再没有则跳转到404 if (mapping == null) { // there is no action in this request, should we look for a static resource? String resourcePath = RequestUtils.getServletPath(request); if ("".equals(resourcePath) && null != request.getPathInfo()) { resourcePath = request.getPathInfo(); } if (staticResourceLoader.canHandle(resourcePath)) { // 在DefaultStaticContentLoader中:return serveStatic && (resourcePath.startsWith("/struts") || resourcePath.startsWith("/static")); staticResourceLoader.findStaticResource(resourcePath, request, response); } else { // this is a normal request, let it pass through chain.doFilter(request, response); } // The framework did its job here return; } //正式开始Action的方法 dispatcher.serviceAction(request, response, servletContext, mapping); } finally { try { ActionContextCleanUp.cleanUp(req); } finally { UtilTimerStack.pop(timerKey); } } }
//下面是ActionMapper接口的实现类 DefaultActionMapper的getMapping()方法的源代码: public ActionMapping getMapping(HttpServletRequest request, ConfigurationManager configManager) { ActionMapping mapping = new ActionMapping(); String uri = getUri(request);//得到请求路径的URI,如:testAtcion.action或testAction.do int indexOfSemicolon = uri.indexOf(";");//修正url的带;jsessionid 时找不到而且的bug uri = (indexOfSemicolon > -1) ? uri.substring(0, indexOfSemicolon) : uri; uri = dropExtension(uri, mapping);//删除扩展名,默认扩展名为action if (uri == null) { return null; } parseNameAndNamespace(uri, mapping, configManager);//匹配Action的name和namespace handleSpecialParameters(request, mapping);//去掉重复参数 //如果Action的name没有解析出来,直接返回 if (mapping.getName() == null) { returnnull; } //下面处理形如testAction!method格式的请求路径 if (allowDynamicMethodCalls) { // handle "name!method" convention. String name = mapping.getName(); int exclamation = name.lastIndexOf("!");//!是Action名称和方法名的分隔符 if (exclamation != -1) { mapping.setName(name.substring(0, exclamation));//提取左边为name mapping.setMethod(name.substring(exclamation + 1));//提取右边的method } } return mapping; }
从代码中看出,getMapping()方法返回ActionMapping类型的对象,该对象包含三个参数:Action的name、namespace和要调用的方法method。
如果getMapping()方法返回ActionMapping对象为null,则FilterDispatcher认为用户请求不是Action,自然另当别论,FilterDispatcher会做一件非常有意思的事:如果请求以/struts开头,会自动查找在web.xml文件中配置的 packages初始化参数,就像下面这样(注意粗斜体部分):
<filter> <filter-name>struts2</filter-name> <filter-class> org.apache.struts2.dispatcher.FilterDispatcher </filter-class> <init-param> <param-name>packages</param-name> <param-value>com.lizanhong.action</param-value> </init-param> </filter>
FilterDispatcher会将com.lizanhong.action包下的文件当作静态资源处理,即直接在页面上显示文件内容,不过会忽略扩展名为class的文件。比如在com.lizanhong.action包下有一个aaa.txt的文本文件,其内容为“中华人民共和国”,访问 http://localhost:8081/Struts2Demo/struts/aaa.txt时会输出txt中的内容
FilterDispatcher.findStaticResource()方法
protectedvoid findStaticResource(String name, HttpServletRequest request, HttpServletResponse response) throws IOException { if (!name.endsWith(".class")) {//忽略class文件 //遍历packages参数 for (String pathPrefix : pathPrefixes) { InputStream is = findInputStream(name, pathPrefix);//读取请求文件流 if (is != null) { ... // set the content-type header String contentType = getContentType(name);//读取内容类型 if (contentType != null) { response.setContentType(contentType);//重新设置内容类型 } ... try { //将读取到的文件流以每次复制4096个字节的方式循环输出 copy(is, response.getOutputStream()); } finally { is.close(); } return; } } } }
如果用户请求的资源不是以/struts开头——可能是.jsp文件,也可能是.html文件,则通过过滤器链继续往下传送,直到到达请求的资源为止。
如果getMapping()方法返回有效的ActionMapping对象,则被认为正在请求某个Action,将调用 Dispatcher.serviceAction(request, response, servletContext, mapping)方法,该方法是处理Action的关键所在。
下面就来看serviceAction,这又回到全局变量dispatcher中了
//Load Action class for mapping and invoke the appropriate Action method, or go directly to the Result. public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context, ActionMapping mapping) throws ServletException { //createContextMap方法主要把Application、Session、Request的key value值拷贝到Map中 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) { extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack)); } String timerKey = "Handling request from Dispatcher"; try { UtilTimerStack.push(timerKey); String namespace = mapping.getNamespace(); String name = mapping.getName(); String method = mapping.getMethod(); Configuration config = configurationManager.getConfiguration(); //创建一个Action的代理对象,ActionProxyFactory是创建ActionProxy的工厂 //参考实现类:DefaultActionProxy和DefaultActionProxyFactory ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy( namespace, name, method, extraContext, true, false); request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack()); // if the ActionMapping says to go straight to a result, do it! //如果是Result,则直接转向,关于Result,ActionProxy,ActionInvocation下一讲中再分析 if (mapping.getResult() != null) { Result result = mapping.getResult(); result.execute(proxy.getInvocation()); } else { //执行Action 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) { // WW-2874 Only log error if in devMode if(devMode) { LOG.error("Could not find action or result", e); } else { 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); } }
发表评论
-
Struts2源码阅读(六)_ActionProxy&ActionInvocation
2009-10-23 22:04 9925下面开始讲一下主菜ActionProxy了.在这之前最好先去了 ... -
Struts2源码阅读(四)_Dispatcher&ConfigurationProvider续
2009-10-20 16:48 3793接下来第三步:init_LegacyStrutsPropert ... -
Struts2源码阅读(三)_Dispatcher&ConfigurationProvider
2009-10-19 21:04 5110首先强调一下struts2的线 ... -
Struts2源码阅读(二)_ActionContext及CleanUP Filter
2009-10-16 16:58 54881. ActionContext ActionContex ... -
Struts2源码阅读(一)_Struts2框架流程概述
2009-10-16 15:25 53201. Struts2架构图 请求首先通过Filter ... -
Struts2中文教程电子书下载
2009-10-16 14:57 4682Struts2中文程程电子书下载 -
在Struts 2.0中国际化(i18n)你的应用程序
2009-10-09 09:29 1411国际化是商业系统中不可或缺的一部分,所以无论您学习的是什么We ... -
OGNL中的#,%,$
2009-10-09 09:14 1348OGNL的用法 OGNL是通常要结合Struts 2的标志 ... -
ValueStack 与 OGNL
2009-10-08 12:53 1922ValueStack 与 OGNL 值栈的含义正如它的名字所 ... -
Struts2 Tags API
2009-10-08 10:57 2770本来想写一篇Struts2 标签的,今天突然得到一份Strut ... -
Struts2 references
2009-10-08 10:22 910Struts2 Guide Home:http://strut ... -
struts.xml配置详解
2009-10-08 09:01 1427<?xml version="1.0" ... -
Struts1与Struts2的特点与比较
2009-10-06 10:57 4202一.MVC的特点:— 多个视图可以对应一个模型。按MVC设计模 ... -
struts.properties详解
2009-10-05 20:49 1139项目中常用的配置如下 struts.objectFactor ... -
Struts2+Spring2.5 web.xml配置
2009-10-05 20:44 2239搭建struts2框架只必需五个jar包:commons-lo ... -
Struts2 源码分析
2009-09-22 19:33 0http://blog.csdn.net/hanxs/arch ...
相关推荐
struts核心过滤器FilterDispatcher介绍,struts核心过滤器FilterDispatcher介绍
org.apache.struts2.dispatcher.FilterDispatcher
Struts 2框架本身大致可以分为3个部分:核心控制器FilterDispatcher、业务控制器Action和用户实现的企业业务逻辑组件。 3.1.1 核心控制器FilterDispatcher 核心控制器FilterDispatcher是Struts 2框架的基础,包含...
Struts 2框架本身大致可以分为3个部分:核心控制器FilterDispatcher、业务控制器Action和用户实现的企业业务逻辑组件。 3.1.1 核心控制器FilterDispatcher 核心控制器FilterDispatcher是Struts 2框架的基础,...
Struts 2框架本身大致可以分为3个部分:核心控制器FilterDispatcher、业务控制器Action和用户实现的企业业务逻辑组件。 核心控制器FilterDispatcher是Struts 2框架的基础,包含了框架内部的控制流程和处理机制。...
Struts2源码分析 请求首先通过Filter chain,Filter 主要包括ActionContextCleanUp,它主要清理当前线 程的ActionContext 和Dispatcher;FilterDispatcher 主要通过AcionMapper 来决定需要调用哪 个Action。
一个请求在Struts 2框架中的处理大概分为以下几个步骤。...Struts 2的核心控制器是FilterDispatcher,有3个重要的方法:destroy()、doFilter()和Init(),可以在Struts 2的下载文件夹中找到源代码,如代码1所示。
第4章 另一Struts2核心技术:拦截器 47 4.1 拦截器在Struts2中的缺省应用 47 4.2 拦截器原理实现 50 4.3 在Struts2中配置自定义的拦截器 53 4.3.1 扩展拦截器接口的自定义拦截器配置 54 4.3.2 继承抽象拦截器的...
我们已在前面学习了Servlet 数据库应用,有了JSP、Servlet 、JDBC的一些知识、理解和应用,也具有了一些MVC...3. 了解核心控制器FilterDispatcher及在web.xml中的配置 4. 了解业务控制器Action及在struts.xml中的配置
Struts 2框架由3个部分组成:核心控制器FilterDispatcher、业务控制器和用户实现的业务逻辑组件。在这3个部分里,Struts 2框架提供了核心控制器FilterDispatcher,而用户需要实现业务控制器和业务逻辑组件。
Struts2执行流程 1. web.xml 部署描述符 2. FilterDispatcher 实现StrutsStatics, Filter接口 (1)Filter:一个filter是一个对象用于执行过滤任务为每个请求资源(一个servlet或静态内容),或响应一个资源,或两者.过滤...
注意ActionContextCleanUp过滤器必须在FilterDispatcher之前配置,ActionContextCleanUp的主要功能是通知FilterDispatcher执行完毕不要清除ActionContext,以便sitemesh装饰器可以访问Struts值堆栈。 配置装饰器 ...
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher, 新版本中都是过时的了,采取该过滤器, <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter。
Struts2的处理流程: • 客户端产生一个HttpServletRequest的请求,该请求被提交到一系列的标准过滤器(Filter)组建链中(如ActionContextCleanUp...FilterDispatcher是控制器的核心,也是MVC中控制层的核心组建)。
2 这个请求经过一系列的过滤器(Filter)(这些过滤器中有一个叫做ActionContextCleanUp的可选过滤器,这个过滤器对于Struts2和其他框架的集成很有帮助,例如:SiteMesh Plugin) 3 接着FilterDispatcher被调用,...
ActionContextCleanUp的可选过滤器,这个过滤器对于Struts2和其他框 架的集成很有帮助,例如:SiteMesh Plugin) 3 接着FilterDispatcher被调用,FilterDispatcher询问ActionMapper来 决定这个请是否需要调用某个...
action command在穿越了一系列Struts2和XWork的拦截器之后,最后执行用户编写的Action类,在Action执行之后,响应还会穿越相同的拦截器(按照与请求相反的顺序),最后通过Struts2的HttpServletResponse转换成Web可...
org.apache.struts2.dispatcher.FilterDispatcher <filter-name>struts2 <url-pattern>/* 7.右击src——new——XML(Advanced Templates)。在File Name中输入struts.xml(必须为此名),单击Finish。Struts...
首先客户端发送HttServletErquest的请求,这个请求经过一系列的过滤器链(Filter),这里是有顺序的,首先经过ActionContext CleanUp,然后再经过其他过滤器(Othter Filters、SiteMesh等),最后再到FilterDispatcher