简体   繁体   English

java servlet中的错误编码(tomcat)

[英]Wrong encoding in java servlet (tomcat)

I am trying to setup the right encoding for my JSP/servlet pages in Tomcat 7. Though, I have to be successful yet. 我正在尝试为Tomcat 7中的JSP / servlet页面设置正确的编码。但是,我必须要成功。 I made some tries from the suggestions given by this stackexchange thread: Character encoding JSP -displayed wrong in JSP but not in URL: "á » á é » é" , but they didn't work. 我根据这个stackexchange线程给出的建议做了一些尝试: 字符编码JSP在JSP中显示错误但在URL中没有显示:“á»Ã»é»Ã©” ,但它们不起作用。 The curious fact lies on the fact that if I let the pages "as is" the browser recognise them as having the encoding Windows-CP 1252 and when I change for UTF-8 the text is displayed correctly. 好奇的事实在于,如果我让页面“按原样”浏览器将其识别为具有编码Windows-CP 1252,并且当我更改为UTF-8时,文本将正确显示。 But applying filters and other mechanisms the browser put the encoding as UTF-8 and is not possibile to display it correctly. 但是应用过滤器和其他机制,浏览器将编码设置为UTF-8,并且无法正确显示它。 In fact for the latter if I change the encoding the results are horrible at minimum. 实际上对于后者,如果我改变编码,结果至少是可怕的。

I got it right now. 我现在就明白了。 In pages JSP I am putting as first instruction: 在我作为第一条指令的JSP页面中:

<%@ page pageEncoding="utf-8" %>

This fixes all problems. 这解决了所有问题。 Other possibilities like to put response.setCharacterEncoding( "UTF-8" ) as first instruction don't work. 将response.setCharacterEncoding(“UTF-8”)作为第一条指令的其他可能性不起作用。

In relation to servlets I need to setup the character encoding before to get the PrintWriter object: 关于servlet,我需要在获取PrintWriter对象之前设置字符编码:

response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();

These things have solved my problem of strange characters. 这些东西解决了我的奇怪角色问题。 To sum up: The problem was that the response coming out from JSP/servlet didn't have pointed that itself was encoded in UTF-8 总结一下:问题是来自JSP / servlet的响应没有指出它本身是用UTF-8编码的

Maybe is not a JSP problem. 也许不是JSP问题。 Have you tried doing that in the page, directly? 您是否尝试直接在页面中执行此操作?

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
...
</head>

Also, try to save the page in UTF-8 format 另外,尝试以UTF-8格式保存页面

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM