有段时间没有使用struts2了,上了官网发现已经更新到2.2.1版本,没有细看note,照着以前老的方式配置web.xml,发现装饰器sitemesh对freemarker不起作用,折腾了一整天。最后还是老老实实看官方的文档,发现以前书上推荐的配置已经过时。老的一般配置如下:
<filter> <filter-name>ActionContextCleanUp</filter-name> <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class> </filter> <filter> <filter-name>sitemesh</filter-name> <filter-class>com.opensymphony.module.sitemesh.filter.PageFilter</filter-class> </filter> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter>
从struts2.1.3开始ActionContextCleanUp 和 FilterDispatcher过滤器,已经不建议使用了。将使用StrutsPrepareFilter 和StrutsExecuteFilter拦截器替代。正确的配置方式如下:
<filter> <filter-name>struts-prepare</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class> </filter> <filter> <filter-name>sitemesh</filter-name> <filter-class>com.opensymphony.sitemesh.webapp.SiteMeshFilter</filter-class> </filter> <filter> <filter-name>struts-execute</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter</filter-class> </filter> <filter-mapping> <filter-name>struts-prepare</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>sitemesh</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> <dispatcher>INCLUDE</dispatcher> </filter-mapping> <filter-mapping> <filter-name>struts-execute</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>sitemesh-freemarker</servlet-name> <servlet-class>org.apache.struts2.sitemesh.FreemarkerDecoratorServlet</servlet-class> <init-param> <param-name>default_encoding</param-name> <param-value>UTF-8</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>sitemesh-freemarker</servlet-name> <url-pattern>*.ftl</url-pattern> </servlet-mapping> <listener> <listener-class>org.apache.struts2.dispatcher.ng.listener.StrutsListener</listener-class> </listener>
注意:
1. com.opensymphony.sitemesh.webapp.SiteMeshFilter这个过滤器是必需的,否则装饰不起作用
2. 为了支持FreeMaker或Velocity,必须添加org.apache.struts2.sitemesh.FreemarkerDecoratorServlet这个Servlet,官方原话:
写道
From 2.2+ the recommended way to use Freemarker with Sitemesh is through the org.apache.struts2.sitemesh.FreemarkerDecoratorServlet servlet
3. 而已从2.2.x开始,必须添加org.apache.struts2.dispatcher.ng.listener.StrutsListener这个监听器
写道
From 2.2+ the new com.opensymphony.sitemesh.webapp.SiteMeshFilter filter and Struts org.apache.struts2.dispatcher.ng.listener.StrutsListener context listener must be added to web.xml,
4. 这样sitemesh装饰器才能在freemarker模板中起作用。