在嵌入式Jetty中设置默认字符编码和内容类型

问题描述 投票:3回答:1

我正在为嵌入式Jetty制作DSL,而我在设置characterEncodingcontentType时遇到了麻烦。我希望用户能够为这两个字段指定默认值,但Jetty正在努力工作。

res.characterEncoding = nullres.characterEncodingiso-8859-1

res.characterEncoding = "",给res.characterEncoding"",但res.contentType成为application/json;charset=

res.characterEncoding = ""然后res.characterEncoding = nullres.characterEncoding = ""有同样的效果

我最终得到了一个基于这种奇怪行为的荒谬的代码片段:

if (res.characterEncoding.contains(";javalin-default") || res.contentType.contains(";javalin-default")) {
    res.contentType = res.contentType.replace(";javalin-default", "")
    res.characterEncoding = null
    if (res.contentType.contains("application/json")) {
        res.contentType = "application/json"
    } else {
        res.characterEncoding = defaultCharacterEncoding
    }
}

但这不是正确的做法。有任何想法吗?

我在这里有一个问题:https://github.com/tipsy/javalin/issues/259

java servlets kotlin jetty embedded-jetty
1个回答
4
投票

您正在与Servlet规范过于复杂的方面进行斗争。

意见:HttpServletResponse.setContentType(String)方法永远不应该存在,它应该只是.setMimeType(String).setCharacterEncoding(Charset)

让我们从字符编码的重要性入手。

访问HttpServletResponse.getWriter()时,实现必须解析用于创建的PrintWriter的响应字符编码和语言环境。这意味着此时的字符编码将分配一个值。

请注意,也使用了语言环境,这经常被忽略,但由于您是库编写者,因此应该向您指出。见HttpServletResponse.setLocale(Locale)HttpServletResponse.getLocale()

还有一点需要考虑的是,如果你已经访问过HttpServletResponse.getWriter(),那么后来使用HttpServletResponse.setCharacterEncoding(String)会导致无操作,并且使用带有HttpServletResponse.setContentType(String)charset会导致charset从生成的标题中被剥离。 (再次,这符合Servlet规范行为)。

如果先前手动设置为有效值,则HttpServletResponse.getCharacterEncoding()可以返回字符编码,如果已经声明,则可以返回Content-Type,否则默认为ISO-8859-1。如果它使用Content-Type,它首先检查charset参数并使用它。如果Content-Type没有charset,那么它会在您的Web元数据中使用mime-type配置。此调用永远不应生成空字符或空字符编码。

使用HttpServletResponse.getCharacterEncoding()的Servlet Spec默认是ISO-8859-1(此值取自RFC2616,当定义了Servlet规范的这一方面时)。

Web元数据来自Web描述符(也称为WEB-INF/web.xml),默认描述符,覆盖描述符,org/eclipse/jetty/http/mime.properties资源,org/eclipse/jetty/http/encoding.properties,其他存在的功能(如GzipHandler)和编程配置。

在Jetty中,mime-type的所有这些各种配置源都会导致配置的Jetty org.eclipse.jetty.http.MimeTypes对象。

当调用HttpServletResponse.setCharacterEncoding(String)时,它还有责任修改响应中的Content-Type字段和标题。

假设尚未调用.getWriter(),使用setCharacterEncoding(null)将删除charset字段和标题上的任何现有Content-Type参数。 setCharacterEncoding("utf-8")会在charset字段和标题上添加/更改utf-8参数到Content-Type

当调用HttpServletResponse.setContentType(String)时,如果提供了charset参数,它还有责任修改字符编码字段。

知道这一切,您就会意识到必须小心各种API调用的顺序,特别是在进行HttpServletResponse.getWriter()调用时。

您可能应该在启动webapp时通过application/json的Web元数据来控制这一点,而不是使用Servlet HttpServletResponse API来管理它。

在你的情况下,你只需要在你的MimeTypes创建的ServletContextHandler上配置JettyServerUtil.kt,不需要你正在使用的任何黑客。

Jetty的ServletContextHandlerMimeTypes配置的默认行为将不会添加字符集,因为application/json资源中定义了org/eclipse/jetty/http/encoding.properties(作为假定的字符集)。

例:

package jetty;

import static java.nio.charset.StandardCharsets.UTF_8;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.IO;

public class MimeTypeJsonExample
{
    public static void main(String[] args) throws Exception
    {
        Server server = new Server(9090);
        ServletContextHandler context = new ServletContextHandler();
        context.setContextPath("/");
        context.addServlet(JsonServlet.class, "/demo");
        context.addServlet(DefaultServlet.class, "/"); // handle static content and errors for this context
        HandlerList handlers = new HandlerList();
        handlers.addHandler(context);
        handlers.addHandler(new DefaultHandler()); // handle non-context errors
        server.setHandler(context);
        server.start();

        try
        {
            demonstrateJsonBehavior(server.getURI().resolve("/"));
        }
        finally
        {
            server.stop();
        }
    }

    private static void demonstrateJsonBehavior(URI serverBaseUri) throws IOException
    {
        HttpURLConnection http = (HttpURLConnection) serverBaseUri.resolve("/demo").toURL().openConnection();
        dumpRequestResponse(http);
        System.out.println();
        try (InputStream in = http.getInputStream())
        {
            System.out.println(IO.toString(in, UTF_8));
        }
    }

    private static void dumpRequestResponse(HttpURLConnection http) throws IOException
    {
        System.out.println();
        System.out.println("----");
        System.out.printf("%s %s HTTP/1.1%n", http.getRequestMethod(), http.getURL());
        System.out.println("----");
        System.out.printf("%s%n", http.getHeaderField(null));
        http.getHeaderFields().entrySet().stream()
                .filter(entry -> entry.getKey() != null)
                .forEach((entry) -> System.out.printf("%s: %s%n", entry.getKey(), http.getHeaderField(entry.getKey())));
    }

    public static class JsonServlet extends HttpServlet
    {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
        {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            resp.setHeader("X-Charset", resp.getCharacterEncoding());
            writer.println("{\"mode\":[\"a=b\"],\"animals\":[[\"kiwi bird\",\"kea\",\"skink\"]]}");
        }
    }
}

这导致输出......

2018-06-27 09:00:32.754:INFO::main: Logging initialized @360ms to org.eclipse.jetty.util.log.StdErrLog
2018-06-27 09:00:32.898:INFO:oejs.Server:main: jetty-9.4.11.v20180605; built: 2018-06-05T18:24:03.829Z; git: d5fc0523cfa96bfebfbda19606cad384d772f04c; jvm 9.0.4+11
2018-06-27 09:00:32.969:INFO:oejsh.ContextHandler:main: Started o.e.j.s.ServletContextHandler@5dd6264{/,null,AVAILABLE}
2018-06-27 09:00:33.150:INFO:oejs.AbstractConnector:main: Started ServerConnector@60707857{HTTP/1.1,[http/1.1]}{0.0.0.0:9090}
2018-06-27 09:00:33.151:INFO:oejs.Server:main: Started @764ms

----
GET http://192.168.0.119:9090/demo HTTP/1.1
----
HTTP/1.1 200 OK
Server: Jetty(9.4.11.v20180605)
X-Charset: utf-8
Content-Length: 58
Date: Wed, 27 Jun 2018 14:00:33 GMT
Content-Type: application/json

{"mode":["a=b"],"animals":[["kiwi bird","kea","skink"]]}

2018-06-27 09:00:33.276:INFO:oejs.AbstractConnector:main: Stopped ServerConnector@60707857{HTTP/1.1,[http/1.1]}{0.0.0.0:9090}
2018-06-27 09:00:33.278:INFO:oejsh.ContextHandler:main: Stopped o.e.j.s.ServletContextHandler@5dd6264{/,null,UNAVAILABLE}

正如你所看到的,JsonServlet只设置了Content-Type mime-type,访问了PrintWriter,设置了一个头X-Charset来显示当前的字符编码值,然后编写了json内容。

客户看到的Content-Type响应头不包括charset的假设utf-8

© www.soinside.com 2019 - 2024. All rights reserved.