解决程序乱码问题(过滤器filter)_jen >>>>> & * >>>> 简_百度空间

程序代码:

package util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class EncodingFilter implements Filter{
String encoding;
public void destroy() {
  
}

//初始化

public void init(FilterConfig config) throws ServletException {
   encoding = config.getInitParameter("encoding");
   System.out.println(encoding);
}

public void doFilter(ServletRequest sReq, ServletResponse sRes,
    FilterChain chain) throws IOException, ServletException {
   HttpServletRequest request = (HttpServletRequest)sReq;
   String m = request.getMethod();
   if("post".equalsIgnoreCase(m)){//如果是post 提交
    System.out.println("post提交");
    request.setCharacterEncoding(encoding);//("utf-8")
   
   }else if("get".equalsIgnoreCase(m)){//get 提交
    //System.out.println("get提交");
    request = new MyRequest(request);
   }
   chain.doFilter(request, sRes);
}


public class MyRequest extends HttpServletRequestWrapper{
   private HttpServletRequest myReq;
   public MyRequest(HttpServletRequest request) {
    super(request);
    myReq = request;
   }
   public String getParameter(String name){
    String s = myReq.getParameter(name);
    //System.out.println("编码转换前:"+s);
    try {
     if(s!=null){
      s = new String(s.getBytes("ISO-8859-1"),"UTF-8");
     }
     //System.out.println("编码转换后: "+s);
    } catch (UnsupportedEncodingException e) {
     e.printStackTrace();
    }
    return s;
   }
}

}

------------------------------------

另外还要在web.xml 中配置:

<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>jenwin.filters.EncodingFilter</filter-class><!--编码转换类-->
<init-param>
   <param-name>encoding</param-name>
   <param-value>utf-8</param-value><!--设置自己的编码方式 -->
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>



郑重声明:资讯 【解决程序乱码问题(过滤器filter)_jen >>>>> & * >>>> 简_百度空间】由 发布,版权归原作者及其所在单位,其原创性以及文中陈述文字和内容未经(企业库qiyeku.com)证实,请读者仅作参考,并请自行核实相关内容。若本文有侵犯到您的版权, 请你提供相关证明及申请并与我们联系(qiyeku # qq.com)或【在线投诉】,我们审核后将会尽快处理。
—— 相关资讯 ——