程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> JSP編程 >> 關於JSP >> 通過過濾器(Filter)解決JSP的Post和Request中文亂碼問題

通過過濾器(Filter)解決JSP的Post和Request中文亂碼問題

編輯:關於JSP

jsp代碼:

import javax.servlet.*;
import javax.servlet.http.*;

public class CharsetFilter implements Filter
{
  public void destroy() 
  {
    
  }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
  {
    try
    {
      HttpServletRequest httpRequest = (HttpServletRequest)request;
      String method = httpRequest.getMethod().toLowerCase();
      if(method.equals("post"))
      {
        //如果是post,即表單方法,直接設置charset即可
        request.setCharacterEncoding("UTF-8");
      }
      else if(method.equals("get"))
      {
        //如果是get方法
        request.setCharacterEncoding("UTF-8");
        request = new HttpServletRequestWrapper((HttpServletRequest)request)
        {
          public String getParameter(String str)
          {
            try
            {
              return new String(super.getParameter(str).getBytes("iso-8859-1"),"GBK");
            }
            catch(Exception e)
            {
              return null;
            }
   
          }
        };
      }
      
      chain.doFilter(request, response);
    }
    catch(Exception e){}
  }
  
  public void init(FilterConfig filterConfig) 
  {
    
  }
}

過濾器配置:

<filter>
    <filter-name>CharFilter</filter-name>
    <filter-class>CharsetFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>CharFilter</filter-name>
    <url-pattern>/*</url-pattern>
    <dispatcher>REQUEST</dispatcher>
</filter-mapping>
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved