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

  之前使用struts1的时候是通过写filter来处理乱码,把写的filter搬到struts2,配置了WEB.XML发生没有效果,请求根本就没有通过filter。原因Struts2在web.html配置了处理action请求的filter:


  struts2
  org.apache.struts2.dispatcher.FilterDispatcher
 

 
  struts2
  /*
 

通过这个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配置

下注册拦截器:

     
        
        
           
           
        
     

3、使用拦截器,可将其设为默认的拦截器
       

4、页面编码和页面字符编码跟设为"GBK"。如果页面是其它编码,将拦截器中重编码部分改一下即可。

你可能感兴趣的:(JAVA学习笔记)