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

Muh*_*edy 4 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>
Run Code Online (Sandbox Code Playgroud)

然后在servlet我使用方法,request.getCharacterEncoding()我得到了null!那么,有没有办法告诉服务器我在一些字符编码中编码数据?

Bal*_*usC 6

这确实会null从大多数网络浏览器返回.但通常你可以放心地假设webbrowser 实际上使用了原始响应头中指定的编码,在这种情况下gb2312.一种常见的方法是创建一个Filter检查请求编码,然后使用ServletRequest#setCharacterEncoding()强制所需的值(当然,您应该在整个Web应用程序中使用该值).

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

将此映射Filterurl-pattern覆盖所有servlet请求,例如/*.

如果你没有这样做并让它去,那么servletcontainer将使用它的默认编码来解析参数,这通常ISO-8859-1是错误的.你的输入????最终会像ÏàÒ˱¾²Ý.