request.getParameter()在get和post方法中文亂碼問題

亂碼緣由:Http請求傳輸時將url以ISO-8859-1編碼,服務器收到字節流後默認會以ISO-8859-1編碼來解碼成字符流(形成中文亂碼)html

post請求:java

假設提交請求的jsp頁面是UTF-8編碼服務器

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>jsp

解決方法1:在服務端獲取參數前,先設置解碼方式。post

//設置解碼方式,對於簡體中文,使用UTF-8解碼
request.setCharacterEncoding("UTF-8"); request.getParameter("參數名");

解決方法2:Tomcat默認編碼ISO8859-1,設置成其餘的編碼編碼

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

解決方法3:經過字符串和字節流轉換時使用正確的編碼獲取中文參數url

String str = new String(request.getParameter("參數名").getBytes("iso-8859-1"), "utf-8"); 

Get請求 ,只有第三種方法有效。spa

相關文章
相關標籤/搜索