问题描述
如何在我对UTF-8的回复中设置默认字符编码?
How do I set the default character encoding on my responses to UTF-8?
我已尝试过
System.setProperty("file.encoding", "UTF-8");
和此
System.setProperty("org.eclipse.jetty.util.UrlEncoding.charset", "utf-8");
两者都没有效果 - 响应仍然随标题发送
Neither has any effect - responses are still sent with the header
Content-Type: text/html; charset=ISO-8859-1
我想为所有text / html响应,并且理想地在代码而不是XML中。我正在使用Jetty 9。
I'd like to do this for all text/html responses, and ideally in code rather than XML. I'm using Jetty 9.
推荐答案
Jetty文档声称它默认使用UTF-8,但似乎是一个谎言。如果你做正常的 response.getWrite()。println(Hello)
,那么内容编码确定如下。
The Jetty documentation claims it uses UTF-8 by default, but that seems to be a lie. If you do the normal response.getWrite().println("Hello")
, then the content encoding is determined as follows.
- 从内容类型到内容编码的默认映射是从
org / eclipse / jetty / http / encoding.properties
:
- A default mapping from content-type to content-encoding is loaded from
org/eclipse/jetty/http/encoding.properties
:
// MimeTypes.java:155
ResourceBundle encoding = ResourceBundle.getBundle("org/eclipse/jetty/http/encoding");
Enumeration<String> i = encoding.getKeys();
while(i.hasMoreElements())
{
String type = i.nextElement();
__encodings.put(type,encoding.getString(type));
}
默认文件为:
text/html = ISO-8859-1
text/plain = ISO-8859-1
text/xml = UTF-8
text/json = UTF-8
-
Response.getWriter()
尝试使用该地图,但默认为ISO-8859-1
Response.getWriter()
tries to use that map, but defaults to ISO-8859-1
@Override
public PrintWriter getWriter() throws IOException
{
if (_outputType == OutputType.STREAM)
throw new IllegalStateException("STREAM");
if (_outputType == OutputType.NONE)
{
/* get encoding from Content-Type header */
String encoding = _characterEncoding;
if (encoding == null)
{
encoding = MimeTypes.inferCharsetFromContentType(_contentType);
if (encoding == null)
encoding = StringUtil.__ISO_8859_1;
setCharacterEncoding(encoding);
}
所以你可以看到 text / html
它不默认为UTF-8。我不认为有一种方法来改变默认从代码。最好的方法是将 encoding.properties
文件更改为:
So you can see that for text/html
it doesn't default to UTF-8. I don't think there is a way of changing the default from code. The best you can do is change the encoding.properties
file to this:
text/html = UTF-8
text/plain = UTF-8
text/xml = UTF-8
text/json = UTF-8
但即使如果找到一个不在其中的编码,它将默认为ISO-8859-1。
But even then if it finds an encoding that isn't in there it will default to ISO-8859-1.
这篇关于Jetty响应字符编码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!