用java過濾器解決中文亂碼_百度文庫
阿新 • • 發佈:2019-01-30
java中文亂碼過濾器2010-10-14 10:56:07| 分類: java | 標籤: |字號大 中 小 訂閱 package filters; import java.io.IOException; 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 TomcatFormFilter implements Filter { /** * Request.java * 對 HttpServletRequestWrapper 進行擴充, 不影響原來的功能並能提供所 有的 HttpServletRequest * 介面中的功能. 它可以統一的對 Tomcat 預設設定下的中文問題進行解決而只 需要用新的 Request 物件替換頁面中的 * request 物件即可. */ class Request extends HttpServletRequestWrapper { public Request(HttpServletRequest request) { super(request); } /** * 轉換由表單讀取的資料的內碼. * 從 ISO 字元轉到 GBK. */ public String toChi(String input) { try { byte[] bytes = input.getBytes("ISO8859-1"); return new String(bytes, "GBK"); } catch (Exception ex) { } return null; } /** * Return the HttpServletRequest holded by this object. */ private HttpServletRequest getHttpServletRequest() { return (HttpServletRequest)super.getRequest(); } /** * 讀取引數 -- 修正了中文問題. */ public String getParameter(String name) { return toChi(getHttpServletRequest().getParameter(name)); } /** * 讀取引數列表 - 修正了中文問題. */ public String[] getParameterValues(String name) { String values[] = getHttpServletRequest().getParameterValues(name); if (values != null) { for (int i = 0; i < values.length; i++) { values[i] = toChi(values[i]); } } return values; } } public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpreq = (HttpServletRequest)request; if(httpreq.getMethod().equals("POST")) { request.setCharacterEncoding("GBK"); } else { request = new Request(httpreq); } chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { } } 本文來自CSDN部落格,轉載請標明出處:http://blog.csdn.net/abs1285/archive/2008/03/30/2231393.aspx