tomcat伺服器8.0版本對於request發出的請求是否默認按照utf-8編碼而不是之前的iso8859-1?

對於之前的tomcat處理器,在處理客戶端的get請求時,一般是通過捕獲客戶端請求數據,比如,得到 String data = request.getParameter("data");

data = new String(data.getBytes("iso8859-1"),"utf-8");這種方式進行亂碼處理的,但是目前對於tomcat處理器,採用如上方式卻得到亂碼,而對獲得的數據不處理卻不亂碼。這是不是因為對於高版本的tomcat處理器對於請求的處理的默認編碼已經發生改變了呢?


你本來的處理方法就是錯誤的。


是的,tomcat8之前默認是ISO8859-1,tomcat8及以後,是UTF-8,這時不需要再另行處理亂碼問題了。參見:Servlet處理get請求時的中文亂碼問題


Tomcat8 URIEncoding默認是UTF-8。

This specifies the character encoding used to decode the URI bytes, after %xx decoding the URL. If not specified, UTF-8 will be used unless the org.apache.catalina.STRICT_SERVLET_COMPLIANCE system property is set to true in which case ISO-8859-1 will be used.


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

data = new String(data.getBytes("xxx"),"utf-8");

URIEncoding 配置的屬性值需要和xxx保持一致就好了。

當然Tomcat 8以後URIEncoding的默認值為UTF-8,8以前為ISO-8859-1


Tomcat對於參數的處理方法為org.apache.catalina.connector.Request#parseParameters

protected void parseParameters() {

// 只在第一次獲取請求參數的時候解析

parametersParsed = true;

// 對請求參數的封裝

Parameters parameters = coyoteRequest.getParameters();

boolean success = false;

try {

// Set this every time in case limit has been changed via JMX

parameters.setLimit(getConnector().getMaxParameterCount());

// getCharacterEncoding() may have been overridden to search for hidden form field containing request encoding // Http Requset Header --&> Content-Type // 這個編碼值可以通過 setCharacterEncoding 方法設置,如果設置了就不會去使用 Content-Type

String enc = getCharacterEncoding();

// 是否配置了useBodyEncodingForURI // 默認為 false 在 Server.xml 里的 Connector 里配置 boolean useBodyEncodingForURI = connector.getUseBodyEncodingForURI();

if (enc != null) {

parameters.setEncoding(enc);

if (useBodyEncodingForURI) {

// 設置請求參數的編碼值 // 如果 useBodyEncodingForURI 為 false,則默認為 UTF-8

parameters.setQueryStringEncoding(enc);

}

} else {

// 默認的編碼方式為ISO-8859-1

parameters.setEncoding

(org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING);

if (useBodyEncodingForURI) {

// 使用默認編碼方式解碼

parameters.setQueryStringEncoding

(org.apache.coyote.Constants.DEFAULT_CHARACTER_ENCODING);

}

}

// 由 Parameters 對象處理請求參數

parameters.handleQueryParameters();

//...

}

}


我遇到了和你同樣的問題。。


為什麼不是在過濾器中處理這事


推薦閱讀:

能否詳細介紹一下字元編碼的發展歷史?
」手機複製這幾個字看你多久能刪完」這句話有什麼秘密能讓人刪不完?
Unicode與bytes有何區別?
程序如何區分該顯示中文字元或英語字元?
字元在內存中最終的表示形式是什麼?是某種字元編碼還是碼位(Code Point)?

TAG:伺服器 | 字元編碼 |