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

解決 JSP 開發中文顯示亂碼的三大方案

     編輯:關於JSP

方案一:頁面指令指定編碼(最常用、最簡單)

<%@ page language="java" pageEncoding="GBK" %>

或使用 contentType:

<%@ page contentType="text/html;charset=gbk" %>

GBK 比 GB2312 支援更多字符,建議優先使用。此法適用於 JSP 頁面本身的中文顯示。

方案二:使用過濾器統一處理請求編碼(推薦用於表單提交、資料庫寫入)

Tomcat 預設採用 ISO-8859-1 編碼處理請求,導致中文參數變亂碼。編寫 SetCharacterEncodingFilter 過濾器可強制指定請求編碼:

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 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 this.ignore = false;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if (ignore || (request.getCharacterEncoding() == null)) {
            String encoding = selectEncoding(request);
            if (encoding != null) request.setCharacterEncoding(encoding);
        }
        chain.doFilter(request, response);
    }

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

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

在 web.xml 註冊:

<!-- SetCharacterEncoding -->
<filter>
    <filter-name>SetCharacterEncoding</filter-name>
    <filter-class>com.struts.common.SetCharacterEncodingFilter</filter-class>
    <init-param>
        <param-name>encoding</param-name>
        <param-value>UTF-8</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>SetCharacterEncoding</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
<!-- SetCharacterEncoding -->

優點:專案層級統一處理,支援國際化(頁面指定 pageEncoding="UTF-8" 即可依 Locale 顯示正確字符集),強烈推薦。

方案三:修改 Tomcat server.xml 的 URIEncoding(針對 URL 參數中文亂碼)

<Connector port="80" URIEncoding="GBK" ... />

Tomcat 5.0+ 版本中,GET 與 POST 處理編碼方式不同,若從 URL 取得中文參數會出現問號。修改 URIEncoding 可解決 GET 請求中文亂碼問題(Tomcat 4.1 無此問題)。

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