Gab*_*ele 29 servlets utf-8 character-encoding query-string
我有一些UTF-8的问题.我的客户端(在GWT中实现)向我的servlet发出请求,URL中有一些参数,如下所示:
http://localhost:8080/servlet?param=value
Run Code Online (Sandbox Code Playgroud)
当我在servlet中检索URL时,我遇到了UTF-8字符的问题.我用这个代码:
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String reqUrl = request.getRequestURL().toString();
String queryString = request.getQueryString();
System.out.println("Request: "+reqUrl + "?" + queryString);
...
Run Code Online (Sandbox Code Playgroud)
所以,如果我打电话给这个网址:
http://localhost:8080/servlet?param=così
Run Code Online (Sandbox Code Playgroud)
结果是这样的:
Request: http://localhost:8080/servlet?param=cos%C3%AC
Run Code Online (Sandbox Code Playgroud)
如何正确设置字符编码?
Bal*_*usC 29
来自HttpServletRequest#getQueryString()javadoc:
返回:包含查询字符串的String;如果URL不包含查询字符串,则返回 null.该值不会被容器解码.
请注意最后一句话.所以你需要使用java.net.URLDecoder对它自己进行URL解码.
String queryString = URLDecoder.decode(request.getQueryString(), "UTF-8");
Run Code Online (Sandbox Code Playgroud)
但是,收集参数的常规方法是使用HttpServletRequest#getParameter().
String param = request.getParameter("param"); // così
Run Code Online (Sandbox Code Playgroud)
如果您已将servletcontainer配置为使用正确的编码,则servletcontainer已经为您进行了URL解码.在request.setCharacterEncoding()对请求主体(POST)不是在请求URI(GET)仅影响.另见Mirage的回答.
sch*_*tic 27
我之前遇到过同样的问题.不确定你正在使用什么Java servlet容器,但至少在Tomcat 5.x中(不确定6.x)该request.setCharacterEncoding()方法对GET参数没有影响.当你的servlet运行时,Tomcat已经解码了GET参数,所以setCharacterEncoding不会做任何事情.
解决这个问题的两种方法:
将连接器的URIEncoding设置更改为UTF-8.请参见http://tomcat.apache.org/tomcat-5.5-doc/config/http.html.
正如BalusC建议的那样,自己解码查询字符串,然后自己将其解析(而不是使用ServletRequest API)到参数映射中.
希望这可以帮助!
Mr_*_*s_D 20
这真的花了一整天但是:
final String param = new String(request.getParameter("param").getBytes(
"iso-8859-1"), "UTF-8");
Run Code Online (Sandbox Code Playgroud)
另见这里.请注意,如果服务器的解码字符集(URIEncoding在tomcat中)为iso-8859-1- 这是有效的- 否则必须传入此字符集.有关如何URIEncoding从server.xmlfor Tomcat 7 获取字符集的示例,请参阅我的引用答案
| 归档时间: |
|
| 查看次数: |
68458 次 |
| 最近记录: |