首先我們看下,一個請求響應的流程
瀏覽器------------------>Servlet容器--------------->顯示頁面
編碼 使用容器的URIEncoding轉碼 解碼
舉例:Tomcat作爲Servlet容器,Tomcat的默認的URIEncoding是“iso8859-1“,可在server.xml配置文件中指定編碼類型
1.JSP中顯示亂碼
解決方法:在JSP中第一行加上<%@ page pageEncoding="UTF-8"%>
即可解決。
2.Servlet中顯示亂碼
解決方法:在Servlet中加上response.setContentType("text/html;charset=UTF-8");
3.Post請求中傳中文參數顯示亂碼
解決方法:接受參數前,加上request.setCharaterEncoding("UTF-8");
4.Get請求中傳中文參數顯示亂碼
第一種解決方法:程序轉碼
String value = new String(pValue.getBytes("iso-8859-1"), "UTF-8");
第二種解決辦法:
解決方法:修改tomcat,conf文件夾下的server.xml文件。將其中的
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"/>
修改爲:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8"/>