首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java J2EE 亂碼問題終極解決方案:Filter 統一編碼過濾器

     編輯:Java 相關知識

前言

亂碼是 J2EE 開發中最常見的痛點,尤其在參數傳遞、表單提交、數據庫交互等環節。單獨處理每個請求不僅繁瑣且易漏。本文提供基於 Filter 的統一編碼過濾器方案,一次配置,全局生效。

1. 亂碼產生原因

  • HTTP 協議默認 ISO-8859-1 編碼傳輸,瀏覽器按頁面編碼(UTF-8/GBK)發送,服務端若不指定編碼解析則產生亂碼。
  • GET 請求參數在 URL 中,POST 請求參數在 Body 中,處理方式不同。
  • 數據庫連接、表、列編碼不一致導致存取亂碼。

2. Filter 統一編碼方案

2.1 過濾器實現類

public class SetCharacterEncodingFilter implements Filter {
    protected String encoding = null;
    protected FilterConfig filterConfig = null;
    protected boolean ignore = true;

    @Override
    public void init(FilterConfig config) throws ServletException {
        this.encoding = config.getInitParameter("encoding");
        String value = config.getInitParameter("ignore");
        if (value == null) this.ignore = true;
        else if (value.equalsIgnoreCase("true")) this.ignore = true;
        else if (value.equalsIgnoreCase("yes")) this.ignore = true;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        // 僅在未設置編碼或強制模式下處理
        if (ignore || request.getCharacterEncoding() == null) {
            String enc = selectEncoding(request);
            if (enc != null) request.setCharacterEncoding(enc);
        }
        chain.doFilter(request, response);
    }

    protected String selectEncoding(ServletRequest request) {
        return this.encoding;
    }

    @Override
    public void destroy() {
        this.encoding = null;
        this.filterConfig = null;
    }
}

2.2 web.xml 配置

<filter>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <filter-class>com.example.filter.SetCharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
    <init-param>
        <param-name>ignore</param-name>
        <param-value>true</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>SetCharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

3. url-pattern 匹配規則詳解

模式含義示例
/默認 Servlet 映射/
/*路徑映射,攔截所有請求/user/login, /api/data
*.do擴展映射,攔截 .do 結尾/user/login.do
/user/*路徑前綴映射/user/list, /user/add

建議:編碼過濾器使用 /* 確保所有請求(包括靜態資源轉發、錯誤頁面)均被處理。

4. 協同配置清單(徹底根治亂碼)

  1. JSP 頁面:<%@ page contentType="text/html;charset=UTF-8" %>
  2. HTML Meta:<meta charset="UTF-8">
  3. JavaScript/Ajax:發送前 encodeURIComponent,服務端已由 Filter 處理。
  4. Tomcat server.xml:<Connector URIEncoding="UTF-8" />(解決 GET 亂碼)。
  5. 數據庫連接串:jdbc:mysql://...?characterEncoding=UTF-8&useUnicode=true
  6. 數據庫/表/列:統一設置 CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci。

5. 常見誤區

  • 在 Filter 中對 request.getParameter() 手動轉碼(new String(param.getBytes("ISO-8859-1"), "UTF-8")),這在 Filter 設置編碼前調用無效,且易出錯。
  • 忽略 ignore 參數導致覆蓋上游已設置的編碼(如 multipart 請求已由 Commons FileUpload 設置)。

總結

配置一個編碼過濾器並設置 encoding=UTF-8、ignore=true、url-pattern=/*,配合 Tomcat URIEncoding、JSP 頁面編碼、數據庫連接編碼,即可從請求入口到數據庫存儲全鏈路統一編碼,徹底消除亂碼困擾。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved