问题描述
我想从请求中获取我的参数(带重音的字符),但它不起作用.我尝试使用 request.setCharacterEncoding("UTF-8")
但它也不起作用.
I want to get my parameters from the request (characters with accents) but it doesn't work. I tried to user request.setCharacterEncoding("UTF-8")
but it didn't work either.
我知道 URLDecoder.decode(request.getQueryString(), "UTF-8")
返回正确的字符,但 request.getParameterValues()
没有工作!
I know that URLDecoder.decode(request.getQueryString(), "UTF-8")
returns the right characters, but request.getParameterValues()
doesn't work!
有人有想法吗?
推荐答案
Paul 的建议似乎是最好的行动方案,但如果您要解决它,则根本不需要 URLEncoder 或 URLDecoder:
Paul's suggestion seems like the best course of action, but if you're going to work around it, you don't need URLEncoder or URLDecoder at all:
String item = request.getParameter("param");
byte[] bytes = item.getBytes(StandardCharsets.ISO_8859_1);
item = new String(bytes, StandardCharsets.UTF_8);
// Java 6:
// byte[] bytes = item.getBytes("ISO-8859-1");
// item = new String(bytes, "UTF-8");
更新:由于这获得了很多选票,我想强调 BalusC 的观点,这绝对不是解决方案;这充其量是一种解决方法.人们不应该这样做.
Update: Since this is getting a lot of votes, I want to stress BalusC's point that this definitely is not a solution; it is a workaround at best. People should not be doing this.
我不知道究竟是什么导致了最初的问题,但我怀疑 URL 已经被 UTF-8 编码,然后又被 UTF-8 编码.
I don't know exactly what caused the original issue, but I suspect the URL was already UTF-8 encoded, and then was UTF-8 encoded again.
这篇关于HttpServletRequest UTF-8 编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!