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

徹底解決 Tomcat 5.0.19 中文亂碼問題:JSP Include 編碼修正與表單提交過濾器方案

     編輯:Java 相關知識

問題一:JSP Include 頁面亂碼

現象

主頁面正常,<jsp:include> 或 `<%@ include %>` 引入的片段出現亂碼。

原因

Tomcat 預設使用 ISO-8859-1 編碼解析 Include 片段,無法正確依據外層 JSP 的 pageEncoding 解析內層中文。

根治方案:修改 Jasper 核心 Jar 預設編碼為 GBK

  1. 下載已修改的 jasper-compiler.jar、jasper-runtime.jar(位於 common/lib)與其他相關 Jar(位於 server/lib)。
  2. 直接覆蓋原檔,重啟 Tomcat 即可從根本解決 Include 編碼問題。

問題二:表單提交資料亂碼

現象

表單 POST/GET 提交的中文參數在 Servlet 端接收為亂碼。

原因

Tomcat 接收請求時未能依請求資訊正確預設編碼。

方案:字符編碼過濾器

package filters;
import java.io.IOException;
import javax.servlet.*;
public class SetCharacterEncodingFilter implements Filter {
    protected String encoding = null;
    protected FilterConfig filterConfig = null;
    protected boolean ignore = true;
    public void destroy() { encoding = null; filterConfig = null; }
    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);
    }
    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
        this.encoding = filterConfig.getInitParameter("encoding");
        String value = filterConfig.getInitParameter("ignore");
        if (value == null) this.ignore = true;
        else if (value.equalsIgnoreCase("true")) this.ignore = true;
        else if (value.equalsIgnoreCase("yes")) this.ignore = true;
        else this.ignore = false;
    }
    protected String selectEncoding(ServletRequest request) { return this.encoding; }
}

web.xml 設定

<filter>
  <filter-name>Set Character Encoding</filter-name>
  <filter-class>filters.SetCharacterEncodingFilter</filter-class>
  <init-param>
    <param-name>encoding</param-name>
    <param-value>GBK</param-value>
  </init-param>
</filter>
<filter-mapping>
  <filter-name>Set Character Encoding</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

總結

  • Include 亂碼:修改 Jasper 核心庫預設編碼,一勞永逸。
  • 表單亂碼:部署編碼過濾器,統一強制設定請求編碼為 GBK。
  • 兩者結合,徹底消除 Tomcat 5.0.19 中文亂碼困擾。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved