ResourceResponse.setCharacterEncoding() 不起作用
我需要在 portlet serveResource()
方法的响应中返回一些特殊的拉丁字母(例如 á
)。 我尝试了以下方法:
response.setCharacterEncoding("ISO-8859-1") ;
PrintWriter out = resWrapper.getWriter();
out.println("á");
out.close();
或者
response.setContentType("text/plain; charset=ISO-8859-1");
PrintWriter out = resWrapper.getWriter();
out.println("á");
out.close();
前端 XHR 调用(对serveResource url)没有从上述任一方法中获取正确的字符。 但是,如果 XHR 将请求发布到 HttpServlet(具有与上面完全相同的响应代码),则它可以正常工作。
有人可以解释一下这里的问题吗?
I need to return some special Latin letter (e.g. á
) in the response of a portlet serveResource()
method. I have tried the following ways:
response.setCharacterEncoding("ISO-8859-1") ;
PrintWriter out = resWrapper.getWriter();
out.println("á");
out.close();
OR
response.setContentType("text/plain; charset=ISO-8859-1");
PrintWriter out = resWrapper.getWriter();
out.println("á");
out.close();
The front end XHR call (to the serveResource url) does not get the correct character back from either approach above. However, if the XHR posts the request to a HttpServlet (with the exact same response codes above), it works fine.
Can someone please shed some light on the problem here?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
浏览器是否有可能根据包含 portlet 的页面上指定的字符集而不是您想要的字符集来解释serveResource() 调用的响应? 也许您得到了正确的字符,但是当浏览器呈现它时,它会忽略您在serveResource()方法中设置的内容,并使用与页面其余部分相同的字符集显示它。
这也许可以解释为什么它与 HttpServlet 一起工作得很好,HttpServlet 负责渲染整个页面,而不仅仅是其中的一部分。 因此,在这种情况下,在响应上设置字符编码就可以解决问题。
Is it possible that the browser is interpreting the response from the serveResource() call according to the character set specified on the page containing the portlet instead of what you intend? Maybe you are getting the correct character back, but when the browser renders it, it disregards what you set in the serveResource() method and displays it with the same character set as the rest of the page.
That might explain why it works fine with an HttpServlet, which has responsibility for rendering the whole page, not just a piece of it. And so, setting the character encoding on the response seals the deal in that case.
我会:
E1
。 如果是这样,则客户端上解释数据的方式存在问题(检查 HTTP 标头)。 如果情况并非如此,则数据编码方式存在问题(编码为 UTF-8,字符变为字节C3 A1
)。out.println(\u00E1");
。如果这有效,则问题在于编译器如何加载和解释 Java 源代码。考虑到 servlet 可以工作,这种情况不太可能发生。I would:
E1
. If this is so, there is something wrong with how the data is being interpreted on the client (check the HTTP headers). If this is not the case, there is a problem with how the data is being encoded (encoded as UTF-8, the character becomes the bytesC3 A1
).out.println(\u00E1");
. If this works, then the problem is in how the compiler loads and interprets the Java source. This is unlikely given that the servlet works.