struts2用拦截器解决中文乱码问题

来源:互联网 发布:医学软件 知乎 编辑:程序博客网 时间:2024/05/20 06:27
  之前使用struts1的时候是通过写filter来处理乱码,把写的filter搬到struts2,配置了WEB.XML发生没有效果,请求根本就没有通过filter。原因Struts2在web.html配置了处理action请求的filter:<filter>  <filter-name>struts2</filter-name>  <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping>  <filter-name>struts2</filter-name>  <url-pattern>/*</url-pattern> </filter-mapping>通过这个sturts filter后,在这个struts filter之前或之后配置都是发现处理乱码的filter不起作用,所以编写拦截器还是个不错的解决乱码的方式。1、编写自定义EncodingIntereptor拦截器import java.io.UnsupportedEncodingException;import java.util.Iterator;import javax.servlet.http.HttpServletRequest;import org.apache.struts2.StrutsStatics;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;public class EncodingInterceptor extends AbstractInterceptor { /**  * Struts2编码拦截器  */  @Override public String intercept(ActionInvocation arg0) throws Exception {  // TODO Auto-generated method stub     ActionContext actionContext = arg0.getInvocationContext();      HttpServletRequest request= (HttpServletRequest) actionContext.get(StrutsStatics.HTTP_REQUEST);   System.out.println("Encoding Intercept...");  /**   * 此方法体对GET 和 POST方法均可   */  if( request.getMethod().compareToIgnoreCase("post")>=0){      try {       request.setCharacterEncoding("GBK");      } catch (UnsupportedEncodingException e) {       // TODO Auto-generated catch block       e.printStackTrace();      }     }else{                  Iterator iter=request.getParameterMap().values().iterator();      while(iter.hasNext())      {       String[] parames=(String[])iter.next();       for (int i = 0; i < parames.length; i++) {        try {         parames[i]=new String(parames[i].getBytes("iso8859-1"),"GBK");//此处GBK与页面编码一样        } catch (UnsupportedEncodingException e) {         e.printStackTrace();        }       }         }          }         return arg0.invoke(); }}2、Struts.xml配置<package>下注册拦截器:     <interceptors>        <interceptor name="Encoding" class="com.disaster.util.EncodingInterceptor"></interceptor>        <interceptor-stack name="Encode">           <interceptor-ref name="Encoding"></interceptor-ref>           <interceptor-ref name="defaultStack"></interceptor-ref><!-- 必须引入这个,否则request不会再往下传-->        </interceptor-stack>     </interceptors>3、使用拦截器,可将其设为默认的拦截器     <default-interceptor-ref name="Encode"></default-interceptor-ref>  4、页面编码和页面字符编码跟设为"GBK"。如果页面是其它编码,将拦截器中重编码部分改一下即可。