Struts2.0所有的配置被整合在一个Filter里面,该Filter位于StrutsPrepareAndExecuteFilter,因此,在web.xml中应该这样声明:
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
但是,该Filter一个问题,就是从页面传到后台的中文经过这个过滤器后会变成乱码,为了解决这个问题,需要重写这个过滤器,最简单的方法是写一个类继承StrutsPrepareAndExecuteFilter,代码如下:
package com.cstp.lifuqiang.filter;
//com.cstp.lifuqiang.filter.MyFilter
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter;
public class MyFilter extends StrutsPrepareAndExecuteFilter {
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
super.doFilter(req, resp, chain);
}
}
这时web.xml中相应的地方就改为:
<filter>
<filter-name>struts2</filter-name>
<filter-class>com.cstp.lifuqiang.filter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>