[英]How to set request encoding in Tomcat?
我的 Java webapp 有問題。
這是 index.jsp 中的代碼:
<%@page contentType="text/html" pageEncoding="UTF-8" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<% request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form action="index.jsp" method="get">
<input type="text" name="q"/>
</form>
Res: <%= request.getParameter("q") %>
</body>
</html>
當我對請求進行wireshark 時,我的瀏覽器會發送此標頭:
GET /kjd/index.jsp?q=%C3%A9 HTTP/1.1\r\n
...
Accept-Charset: UTF-8,*\r\n
Tomcat 服務器返回給我:
Content-Type: text/html;charset=UTF-8\r\n
但是,如果我在表單中發送“é”(UTF-8 中的 %C3%A9),則會顯示“é”。
我的理解是瀏覽器發送了一個用 UTF-8(%C3%A9)編碼的“é”。
但服務器將其解釋為 ISO-8859-1。 所以 %C3 被解碼為 Ã , %A9 被解碼為 ©,然后發回以 UTF-8 編碼的響應。
在代碼中,請求應使用 UTF-8 解碼:
request.setCharacterEncoding("UTF-8");
但是,如果我發送這個網址:
http://localhost:8080/kjd/index.jsp?q=%E9
“%E9”用 ISO-8859-1 解碼並顯示“é”。
為什么這不起作用? 為什么使用 ISO-8859-1 解碼請求?
我已經在 Tomcat 6 和 7 以及 Windows 和 Ubuntu 上試過了。
request.setCharacterEncoding("UTF-8");
只設置請求正文的編碼(POST 請求使用),而不設置請求URI的編碼(GET 請求使用)。
您需要在 Tomcat 的/conf/server.xml
的<Connector>
元素/conf/server.xml
URIEncoding
屬性設置為UTF-8
,以使 Tomcat 將請求 URI(和查詢字符串)解析為 UTF-8。 這確實默認為 ISO-8859-1。 另請參閱Tomcat HTTP 連接器文檔。
<Connector ... URIEncoding="UTF-8">
或確保使用與正文1相同的編碼解析 URI:
<Connector ... useBodyEncodingForURI="true">
1來自Tomcat 的文檔(重點是我的):
存在此設置是為了與 Tomcat 4.1.x 兼容,其中在 contentType 中指定的編碼或使用 Request.setCharacterEncoding 方法顯式設置的編碼也用於來自 URL 的參數。 默認值為假。
請在您的 JSP 中去掉那些scriptlet 。 request.setCharacterEncoding("UTF-8");
在錯誤的時刻被調用。 每當您正確使用 Servlet 來處理請求時,就為時已晚。 您更願意為此使用過濾器。 response.setCharacterEncoding("UTF-8");
部分已經由 JSP 頂部的pageEncoding="UTF-8"
隱式完成。
我還強烈建議用EL ${param.q}
或JSTL XML 轉義${fn:escapeXml(param.q)}
舊式<%= request.getParameter("q") %>
scriptlet以防止XSS 攻擊。
您只需要在 conf/web.xml ( Tomcat 服務器web.xml
) 中取消注釋以下部分代碼,該部分將過濾所有請求並轉換為 UTF-8。
<!-- A filter that sets character encoding that is used to decode -->
<!-- parameters in a POST request -->
<filter>
<filter-name>setCharacterEncodingFilter</filter-name>
<filter-class>org.apache.catalina.filters.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<!-- The mapping for the Set Character Encoding Filter -->
<filter-mapping>
<filter-name>setCharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
而已。 在 tomcat 中工作正常
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.