首先了解FilterDispatcher和StrutsPrepareAndExecuteFilterhtml
FilterDispatcher是struts2.0.x到2.1.2版本的核心过滤器.
StrutsPrepareAndExecuteFilter是自2.1.3开始就替代了FilterDispatcher的.
StrutsPrepareAndExecuteFilter是StrutsPrepareFilter和StrutsExecuteFilter的组合,那何时用StrutsPrepareFilter和StrutsExecuteFilter的组合来替代StrutsPrepareAndExecuteFilter呢?下面会讲到。
这样的改革固然是有好处的.
为何这么说.? 应该知道若是咱们本身定义过滤器的话, 是要放在strtus2的过滤器以前的, 若是放在struts2过滤器以后,你本身的过滤器对action的过滤做用就废了,不会有效!除非你是访问jsp/html!
那我如今有需求, 我必须使用Action的环境,而又想在执行action以前拿filter作一些事, 用FilterDispatcher是作不到的.!
那么StrutsPrepareAndExecuteFilter能够把他拆分红StrutsPrepareFilter和StrutsExecuteFilter,能够在这两个过滤器之间加上咱们本身的过滤器.!
给你打个比喻, 如今有病人要作手术, 如今struts2要作两件事, 搭病床(环境),执行手术.! 那么打麻药的工做呢.? 不可能要病人站着打吧, 因此必须有病床的环境,打完麻药以后再动手术.! 这个比喻很是形象了.!
ActionContextCleanUp的做用是延长action中属性的生命周期
自定义本身的filter: 在web.xml中要把咱们本身定义的过滤器放在StrutsPrepareFilter和StrutsExecuteFilter之间。
这样咱们本身定义的过滤器就能像在action中使用Action的环境web
而后了解ActionContextCleanUpapache
通常状况下,若是你要用SiteMesh或者其余过滤器,通常是放在FilterDispatcher或者是如今的StrutsPrepareAndExecuteFilter以前。在调用完全部过滤器的doFilter方法后,核心过滤器FilterDispatcher或者StrutsPrepareAndExecuteFilter会清空ActionContext,若是其余过滤器要一直使用value stack等struts的特性时,若是不用ActionContextCleanUp的话,便得不到想要的值。 ActionContextCleanUp的做用就是上面用粗体标注出来的那一句。它会在doFilter方法里设置一个计数器counter的初始值为1,有了这个值,后续的核心过滤器就不会清空ActionContext,而是由以前的过滤器也就是ActionContextCleanUp来清空ActionContext。app
因此咱们引入struts2,须要在struts2中引入StrutsPrepareAndExecuteFilter和ActionContextCleanUp这2个过滤器便可。jsp
<filter> <filter-name>struts-cleanup</filter-name> <filter-class> org.apache.struts2.dispatcher.ActionContextCleanUp </filter-class> </filter> <filter-mapping> <filter-name>struts-cleanup</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> </filter> <!-- stusts过滤action,若是所有过滤则webservice没法发布 --> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.action</url-pattern> </filter-mapping> <!-- stusts过滤jsp,不然页面报错 --> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/jsp/*</url-pattern> </filter-mapping>