码头响应字符编码

Tim*_*mmm 5 java encoding content-type jetty character-encoding

如何在对UTF-8的回复中设置默认字符编码?

我已经试过了

    System.setProperty("file.encoding", "UTF-8");
Run Code Online (Sandbox Code Playgroud)

和这个

    System.setProperty("org.eclipse.jetty.util.UrlEncoding.charset", "utf-8");
Run Code Online (Sandbox Code Playgroud)

都不起作用-响应仍与标头一起发送

Content-Type: text/html; charset=ISO-8859-1
Run Code Online (Sandbox Code Playgroud)

我想对所有text / html响应执行此操作,理想情况下是使用代码而不是XML。我正在使用Jetty 9。

Tim*_*mmm 7

Jetty 文档声称它默认使用 UTF-8,但这似乎是一个谎言。如果你做 normal response.getWrite().println("Hello"),那么内容编码确定如下。

  1. 从内容类型到内容编码的默认映射从以下位置加载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));
        }
Run Code Online (Sandbox Code Playgroud)

默认文件是:

text/html   = ISO-8859-1
text/plain  = ISO-8859-1
text/xml    = UTF-8
text/json   = UTF-8
Run Code Online (Sandbox Code Playgroud)
  1. Response.getWriter() 尝试使用该地图,但默认为 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);
        }
Run Code Online (Sandbox Code Playgroud)

所以你可以看到,因为text/html它没有默认为 UTF-8。我认为没有办法从代码中更改默认值。您能做的最好的事情是将encoding.properties文件更改为:

text/html   = UTF-8
text/plain  = UTF-8
text/xml    = UTF-8
text/json   = UTF-8
Run Code Online (Sandbox Code Playgroud)

但即便如此,即使它找到了不存在的编码,它也会默认为 ISO-8859-1。