我正在尝试将包含 unicode 字符的简单表单发布到 servlet 操作。在 Jetty 上,一切顺利。在 Tomcat 服务器上,utf-8 字符会被破坏。
我遇到的最简单的情况:
表格:
<form action="action" method="post">
<input type="text" name="data" value="It’s fine">`
</form>`
行动:
class MyAction extends ActionSupport {
public void setData(String data) {
// data is already mangled here in Tomcat
}
}
- 我在
<Connector>
上有 URIEncoding="UTF-8"在 server.xml 中 - 操作调用的第一个过滤器 request.setCharacterEncoding("UTF-8");
- 包含表单的页面的内容类型是“text/html; charset=UTF-8”
- 在表单中添加“accept-charset”没有任何区别
我能让它工作的唯一两种方法是使用 Jetty 或将其切换为 method="get"。这两者都会使字符顺利通过。
最佳答案
I've got URIEncoding="UTF-8" on
<Connector>
in server.xml
这仅与 GET 请求相关。
The first filter on the action calls
request.setCharacterEncoding("UTF-8");
很好,这应该适用于 POST 请求。您只需要确保如果您没有调用 getParameter()
, getReader()
, getInputStream()
或任何其他会在调用setCharacterEncoding()
之前触发解析请求主体的东西.
The content type of the page that contains the form is
"text/html; charset=UTF-8"
您究竟是如何设置的?如果在 <meta>
中完成,那么您需要了解,当通过 HTTP 和 HTTP Content-Type
提供页面时,浏览器会忽略。存在响应 header 。一般的网络服务器已经默认设置了它。 <meta>
内容类型将仅在页面保存到本地磁盘并从那里查看时使用。
要正确设置响应 header 字符集,请将以下内容添加到您的 JSP 顶部:
<%@page pageEncoding="UTF-8" %>
顺便说一句,这也会告诉服务器以给定的字符集发送响应。
Adding "accept-charset" to the form makes no difference
它只在 MSIE 中有所不同,但即便如此,它还是错误地使用了它。无论如何,整个属性一文不值。算了。
另见:
关于java - UTF-8 编码使用 Tomcat 提交的 servlet 表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8391675/