为什么在java中使用request.getParameter()时字符被损坏了? [英] Why the character is corrupted when use request.getParameter() in java?

查看:22
本文介绍了为什么在java中使用request.getParameter()时字符被损坏了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JSP页面中有这样一个链接,编码为big5http://hello/world?name=婀ㄉ当我在浏览器的 URL 栏中输入它时,它会变成类似http://hello/world?name=%23%24%23而当我们想在jsp页面中获取这个参数时,所有的字符都被破坏了.

I have such a link in JSP page with encoding big5 http://hello/world?name=婀ㄉ And when I input it in browser's URL bar, it will be changed to something like http://hello/world?name=%23%24%23 And when we want to get this parameter in jsp page, all the characters are corrupted.

我们已经设置了这个:request.setCharacterEncoding("UTF-8"),所以所有的请求都会被转换成UTF8.

And we have set this: request.setCharacterEncoding("UTF-8"), so all the requests will be converted to UTF8.

但为什么在这种情况下,它不起作用?提前致谢!

But why in this case, it doesn't work ? Thanks in advance!.

推荐答案

当您在浏览器地址栏中输入 URL 时,浏览器可能会先转换字符编码,然后再进行 URL 编码.但是,这种行为没有明确定义,请参阅我的问题,

When you enter the URL in browser's address bar, browser may convert the character encoding before URL-encoding. However, this behavior is not well defined, see my question,

在 Tomcat 上处理 URI 中的字符编码

我们在较新的浏览器上主要使用 UTF-8 和 Latin-1,但我们在旧浏览器中使用各种编码(包括 Big5).所以最好避免用户直接输入的 URL 中的非 ASCII 字符.

We mostly get UTF-8 and Latin-1 on newer browsers but we get all kinds of encodings (including Big5) in old ones. So it's best to avoid non-ASCII characters in URL entered by user directly.

如果 URL 是嵌入在 JSP 中的,你可以像这样生成它,将其强制转换为 UTF-8,

If the URL is embedded in JSP, you can force it into UTF-8 by generating it like this,

String link = "http://hello/world?name=" + URLEncoder.encode(name, "UTF-8");

在Tomcat上,需要像这样在Connector上指定编码,

On Tomcat, the encoding needs to be specified on Connector like this,

<Connector port="8080" URIEncoding="UTF-8"/>

您还需要使用 request.setCharacterEncoding("UTF-8") 进行正文编码,但在 servlet 中设置它是不安全的,因为这仅在未处理参数但其他过滤器时有效或阀门可能会触发处理.所以你应该在过滤器中进行.Tomcat 在源码分发中自带这样的过滤器.

You also need to use request.setCharacterEncoding("UTF-8") for body encoding but it's not safe to set this in servlet because this only works when the parameter is not processed but other filter or valve may trigger the processing. So you should do it in a filter. Tomcat comes with such a filter in the source distribution.

这篇关于为什么在java中使用request.getParameter()时字符被损坏了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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