解決JavaEE項目tomcat中文亂碼問題【最全方案】

一、Request請求中文參數亂碼問題解決方案:

1、GET請求中文參數值亂碼問題解決:

    a)解決亂碼的核心思路,就是把得到的亂碼按照原來亂碼的步驟逆序操作。

    1、先以iso-8895-1進行編碼

    2、然後再以utf-8進行解碼

    3、代碼示例:

        String username = request.getParameter("username");       

        username = new String(username.getBytes("ISO-8859-1"), "UTF-8");

     b)配置tomcat的server.xml配置文件,找到以下位置,新增 URIEncoding = "UTF-8"。

       <Connector URIEncoding = "UTF-8" port="8080" protocol="HTTP/1.1" 
               connectionTimeout="20000" 
               redirectPort="8443" />

2、POST請求中文參數值亂碼問題解決

    POST請求方式亂碼的原因是:Tomcat服務器對參數的默認編碼是ISO-8859-1

    POST請求亂碼解決,只需要在獲取請求參數之前調用 request.setCharacterEncoding("UTF-8"); 方法設置字符集 即可。

    注意點:setCharacterEncoding必須要獲取請求參數之前調用纔有效。

二、Response服務器和客戶端中文亂碼問題

    設置服務器的字符串編碼

      //設置服務器輸出的編碼爲UTF-8

    response.setCharacterEncoding("UTF-8");

    設置客戶端的字符串顯示編碼。

   //告訴瀏覽器輸出的內容是html,並且以utf-8的編碼來查看這個內容。

   response.setHeader(“Content-type”, “text/html; charset=UTF-8”);

    同時設置服務器和客戶端的字符串編碼(推薦)。

    response.setContentType("text/html;charset=utf-8");

三、採用過濾器解決編碼問題

    方案一和方案二可以解決單個程序的編碼問題,對於整個項目來講,建議使用過濾器解決編碼問題。

    我們可以自己動手編寫自己的編碼過濾器,步驟如下:

1、編寫自己的過濾器:


package com.test.filter;

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;


public class CharacterEncodingFilter implements Filter
{
    @SuppressWarnings("unused")
    private FilterConfig config;
    private String encoding;

    public void destroy()
    {

    }

    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException
    {
        request.setCharacterEncoding(encoding);
        response.setContentType("text/html;charset=utf-8");
        chain.doFilter(request, response);

    }

    public void init(FilterConfig config) throws ServletException
    {
        this.config = config;
        this.encoding = config.getInitParameter("encoding");
    }

}
 

2、web.xml做如下配置:


<filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>
            com.test.filter.CharacterEncodingFilter
        </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章