servlet知道使用http-equiv指定的发送表单的编码吗? [英] Does a servlet know the encoding of the sent form that specified using http-equiv?

查看:106
本文介绍了servlet知道使用http-equiv指定的发送表单的编码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Does a servlet knows the encoding of the sent form that specified using http-equiv?

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

When I specify an encoding of a POSTed form using http-equiv like that:

<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
所以,有一种方法,我可以告诉服务器,我编码的数据在一些char编码

And then at the servlet I use the method, request.getCharacterEncoding() I got null ! So, Is there a way that I can tell the server that I am encoding the data in some char encoding??

推荐答案

这将从大多数webbrowser中返回 null 。但通常你可以安全地假设webbrowser已经实际上使用了原始响应头中指定的编码,在这种情况下, gb2312 。一种常见的方法是创建一个 Filter ,它检查请求编码,然后使用 ServletRequest#setCharacterEncoding() (ServletRequest请求,ServletResponse响应),并且强制使用所需的值(您当然应该在整个Web应用程序中一致使用它)。

This will indeed return null from most webbrowsers. But usually you can safely assume that the webbrowser has actually used the encoding as specified in the original response header, which is in this case gb2312. A common approach is to create a Filter which checks the request encoding and then uses ServletRequest#setCharacterEncoding() to force the desired value (which you should of course use consistently throughout your webapplication).

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

映射此过滤器在覆盖所有servlet请求的 url-pattern 上,例如 / *

Map this Filter on an url-pattern covering all servlet requests, e.g. /*.

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

If you didn't do this and let it go, then the servletcontainer will use its default encoding to parse the parameters, which is usually ISO-8859-1, which in turn is wrong. Your input of 相宜本草 would end up like ÏàÒ˱¾²Ý.

这篇关于servlet知道使用http-equiv指定的发送表单的编码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆