java - servlet 是否知道使用 http-equiv 指定的已发送表单的编码?

标签 java encoding servlets character-encoding

servlet 是否知道使用 http-equiv 指定的发送表单的编码?

当我像这样使用 http-equiv 指定 POSTed 表单的编码时:

<HTML>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=gb2312'/>
</head>
<BODY >
<form name="form" method="post" >
    <input type="text" name="v_rcvname" value="相宜本草">
</form>
</BODY>
</HTML>

然后在 servlet 中我使用方法 request.getCharacterEncoding() 我得到了 null ! 那么,有没有一种方法可以告诉服务器我正在用某种字符编码对数据进行编码?

最佳答案

这确实会从大多数网络浏览器返回 null。但通常您可以安全地假设网络浏览器实际上使用了原始响应 header 中指定的编码,在本例中为gb2312。一种常见的方法是创建一个 Filter 来检查请求编码,然后使用 ServletRequest#setCharacterEncoding()强制使用所需的值(您当然应该在整个网络应用程序中始终如一地使用它)。

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
    if (request.getCharacterEncoding() == null) {
        request.setCharacterEncoding("gb2312");
    }
    chain.doFilter(request, response);
}

将此 Filter 映射到覆盖所有 servlet 请求的 url-pattern 上,例如/*

如果你没有这样做而让它过去,那么servletcontainer会使用它的默认编码来解析参数,通常是ISO-8859-1,这反过来又是错误的。您输入的 相宜本草 最终会像 ÏàÒȱ¾²Ý

关于java - servlet 是否知道使用 http-equiv 指定的已发送表单的编码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2861886/

相关文章:

java - Spring Integration - MongoDB 入站 channel 读取相同的数据

java - 使用 Apache CXF 调用 SOAP API 时发生 ClassCastException

java - 选择正确的系列

java - 给定字节数的最大字符串长度

servlets - request.getQueryString() 似乎需要一些编码

java - 发送动态生成的javascript文件

java - 在Spring Boot中的requestmapping和restcontroller中发送开始和结束日期

ruby - ActionMailer 字符串编码

python - 从文本文件读取时的 Unicode 编码

html - 将 Json 对象添加到 url