Java 如何在 tomcat 中使用 UTF-8
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9822663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use UTF-8 with tomcat
提问by idrosid
Tomcat does not encode correctly String literals that contain unicode characters. The problem occurs at a Linux server but not on my development machine (Windows). It affects ONLY String literals (not Strings read from DB or from file!!!).
Tomcat 未正确编码包含 unicode 字符的字符串文字。问题发生在 Linux 服务器上,但不在我的开发机器 (Windows) 上。它只影响字符串文字(不影响从数据库或文件读取的字符串!!!)。
- I have set the
URIEncoding="utf-8"
at the Connector tag (server.xml). - I have used setCharacterEncoding().
- I cheched the stack trace (no filters that might set encoding).
- I have set the LANG environment variable
- I cheched the HTTP Headers and they are correct (Content-Type=text/plain;charset=utf-8)
- I checked the encoding at the browser and it is correct (UTF-8)
- 我已
URIEncoding="utf-8"
在连接器标记 (server.xml) 中设置了。 - 我使用过 setCharacterEncoding()。
- 我检查了堆栈跟踪(没有可能设置编码的过滤器)。
- 我已经设置了 LANG 环境变量
- 我检查了 HTTP 标头,它们是正确的 (Content-Type=text/plain;charset=utf-8)
- 我在浏览器上检查了编码,它是正确的(UTF-8)
Nothing of the above works. Any ideas on what I might be missing?
以上都不起作用。关于我可能缺少什么的任何想法?
public class Test extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/plain;");
Writer w = resp.getWriter();
w.write("Μαλακ?α Latin"); //Some unicode characters
w.close();
}
The above shows this at the browser. ??????·???1?o?? Latin
上面在浏览器中显示了这一点。??????????1?o?? 拉丁
采纳答案by benmmurphy
You can force the encoding of files when javac reads them by passing in -encoding 'utf-8' or -encoding 'iso-8859-1' when compiling. Just make sure that it matches whatever encoding your .java files are actually encoded as.
您可以通过在编译时传入 -encoding 'utf-8' 或 -encoding 'iso-8859-1' 来强制在 javac 读取文件时对文件进行编码。只要确保它与您的 .java 文件实际编码为的任何编码相匹配。
http://docs.oracle.com/javase/6/docs/technotes/tools/windows/javac.html
http://docs.oracle.com/javase/6/docs/technotes/tools/windows/javac.html
-encoding encoding Set the source file encoding name, such as EUC-JP and UTF-8. If -encoding is not specified, the platform default converter is used.
-encoding encoding 设置源文件编码名称,如EUC-JP 和UTF-8。如果未指定 -encoding,则使用平台默认转换器。
回答by Bruno Grieder
Try setting the file.encoding system property e.g. -Dfile.encoding=utf-8
on the Linux JVM command line
尝试设置 file.encoding 系统属性,例如-Dfile.encoding=utf-8
在 Linux JVM 命令行上