ISO-8859-1 编码 URL 无法被 Tomcat 中的 Servlet 正确解码 8

ISO-8859-1 encoded URL can't be correctly decoded by Servlet in Tomcat 8

我有一个这么简单的 Servlet:

public class MyServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("processedName", request.getParameter("name"));
        request.setAttribute("processedQueryString", request.getQueryString());
        request.getRequestDispatcher("index.jsp").forward(request, response);
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

我的index.jsp是这样的:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Title</title>
</head>
<body>
    <form action="MyServlet" method="get">
        Name: <input type="text" name="name">
        <input type="submit" value="Submit">
    </form>
    <br>
    After: <%=request.getAttribute("processedName") %>
    <br>
    Query String: <%=request.getAttribute("processedQueryString") %>
</body>
</html>

如果我在表单中输入 Thomás 并提交,则会打印 Thom?s

浏览器中的 URL 和 JSP 中的查询字符串都显示 name=Thom%E1s

浏览器将 ISO-8859-1 á 字符正确编码为 %E1,但由于某些原因 .getParameter 未正确解码。

当人们尝试提交非 ISO-8859-1 字符时(与 á 不同),我在这里看到了很多像这样的 post。 Tomcat 8 不应该使用 ISO-8859-1 作为解码的默认值吗?

奇怪的是,如果我在我的表单中输入 accept-charset="UTF-8",它就会起作用。如果我将方法更改为 method="post" 它会起作用。如果我混合使用 accept-charset="UTF-8"method="post" 它不起作用(但现在 Thomás 被打印了!)。

好像Tomcat在get方法中等待UTF-8,在post方法中等待ISO-8859-1。

tomcat 8 中的默认 URIEncoding 是 UTF-8,除非 属性 org.apache.catalina.STRICT_SERVLET_COMPLIANCE 设置为 true,则它是 ISO-8859-1。

对于您的情况,您可以尝试添加以下内容:

 URIEncoding="ISO-8859-1"

在您的 server.xml 文件中连接器元素。

有关所有详细信息,请参阅 tomcat documentation