1. 程式人生 > >關於get和post請求中文亂碼的解決辦法

關於get和post請求中文亂碼的解決辦法

web專案中經常遇到中文亂碼問題,本文簡單記錄遇到中文亂碼問題時的解決方案,程式碼如下:

<form class="form-horizontal" role="form" action="${pageContext.request.contextPath}/addProductType.do" >
<div class="modal-header">
	<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
	<h4 class="modal-title" id="proAddLabel">產品型別新增</h4>
</div>
	<div class="modal-body">
		<div class="form-group">
			<label for="productName4Add" class="col-lg-2 control-label">型別名稱</label>
			<div class="col-lg-10">
				<input type="text" class="form-control" id="productName4Add" name = "productTypeName" placeholder="型別名稱">
			</div>
		</div>
	</div>
	<div class="modal-footer">
		<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
		<input type="submit" class="btn btn-primary" value="新增" />
	</div>
</form>

我們可以看到這是一段典型的form表單提交的程式碼,在後臺中我們通過request請求獲取輸入框內的值,這時輸入中文字元後出現亂碼。(在查詢問題之前,先確保eclipse的字符集和jsp頁面的字元編碼均為utf-8)

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

eclipse檢查方式window>preferences>General>Workspace。

確保無誤後進行下面的操作,我們首先想到的是在通過request物件獲取引數前,設定utf-8編碼

request.setCharacterEncoding("utf-8");
String typeName=request.getParameter("productTypeName");
嘗試後亂碼問題依然存在,隨後在form表單中加上method="post"後問題解決。
<form class="form-horizontal" role="form" action="${pageContext.request.contextPath}/addProductType.do"  method="post">
問題總結如下:

先前form表單中沒有設定提交請求的方式,預設為get請求,使用get請求時,請求引數回被附加在url地址後並傳給伺服器,tomcat會先自動解析get請求傳送過來的url字元

串(暫時先這麼理解,後續有進一步瞭解後會對本片進行更新),而tomcat對網路請求處理時的預設字符集是ISO8859-1,這種情況下必定是會出現亂碼的。

當form表單提交請求方式為post時,在獲取request中的引數前加上request.setCharacterEncoding("utf-8")可以有效解決亂碼問題。

request.setCharacterEncoding("utf-8");
String typeName=request.getParameter("productTypeName");

那麼對於get請求,我們如何避免中文字元亂碼呢?我們可以在tomcat的配置檔案中進行字元編碼的修改,tomcat安裝目錄>conf>server.xml中找到下面這行標籤

<Connector port="8080" protocol="HTTP/1.1"   connectionTimeout="20000"   redirectPort="8443" />
在這個標籤中加上URIEcoding="UTF-8"即修改預設字元編碼為utf-8。
<Connector port="8080" protocol="HTTP/1.1"   connectionTimeout="20000"   redirectPort="8443"  URIEcoding="UTF-8" />

除了上述方法,還可以吧原有的引數拆分成byte陣列後再通過該陣列生成指定編碼的String,這是一個萬能的方法
String productTypeName=request.getParameter("productTypeName");
byte[] bytes=str.getBytes("ISO-8859-1");
productTypeName=newString(bytes,"utf-8");