java – 在嵌入式Jetty中设置默认字符编码和内容类型
作者:互联网
我正在为嵌入式Jetty制作DSL,我在设置characterEncoding和contentType时遇到了麻烦.我希望用户能够为这两个字段指定默认值,但Jetty正在努力工作.
res.characterEncoding = null给res.characterEncoding值iso-8859-1.
res.characterEncoding =“”,给res.characterEncoding值“”,但res.contentType变为application / json; charset =
res.characterEncoding =“”THEN res.characterEncoding = null与res.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
解决方法:
您正在与Servlet规范过于复杂的方面进行斗争.
Opinion: The
HttpServletResponse.setContentType(String)
method should never have existed, it should have just been.setMimeType(String)
and.setCharacterEncoding(Charset)
让我们从字符编码的重要性入手.
当访问HttpServletResponse.getWriter()时,实现必须解析用于创建的PrintWriter的响应字符编码和语言环境.这意味着此时的字符编码将分配一个值.
请注意,也使用了语言环境,这经常被忽略,但由于您是库编写者,因此应该向您指出.请参阅HttpServletResponse.setLocale(Locale)和HttpServletResponse.getLocale().
还有一点要考虑的是,如果你已经访问过HttpServletResponse.getWriter(),那么稍后使用HttpServletResponse.setCharacterEncoding(String)会产生一个no-op,并且使用带有charset的HttpServletResponse.setContentType(String)会导致charset被剥离出来的标题. (再次,这符合Servlet规范行为).
如果先前手动设置为有效值,则HttpServletResponse.getCharacterEncoding()可以返回字符编码,如果已经声明,则可以返回Content-Type,否则默认为ISO-8859-1.如果它使用Content-Type,它首先检查charset参数并使用它.如果Content-Type没有charset,那么它将使用Web元数据中的mime类型配置.此调用永远不应生成空字符或空字符编码.
Servlet Spec默认使用HttpServletResponse.getCharacterEncoding()是ISO-8859-1(当定义Servlet规范的这个方面时,此值取自RFC2616).
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)将删除Content-Type字段和标头上的任何现有charset参数. setCharacterEncoding(“utf-8”)会在Content-Type字段和标题上将charset参数添加/更改为utf-8.
当调用HttpServletResponse.setContentType(String)时,如果提供了charset参数,它还有责任修改字符编码字段.
知道了这一切,您就会意识到必须小心各种API调用的顺序,特别是在进行HttpServletResponse.getWriter()调用时.
您可能应该通过webapp启动时application / json的Web元数据来控制它,而不是使用Servlet HttpServletResponse API来管理它.
在您的情况下,您只需在JettyServerUtil.kt创建的ServletContextHandler上配置MimeTypes,不需要使用任何hack.
由于在org / eclipse / jetty / http / encoding.properties资源中定义了application / json(作为假定的字符集),Jetty的ServletContextHandler和MimeTypes配置的默认行为将不会添加字符集.
例:
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类型,访问PrintWriter,设置标头X-Charset以显示当前字符编码值,然后编写json内容.
客户端看到的Content-Type响应头不包括utf-8的假定字符集.
标签:java,kotlin,embedded-jetty,servlets,jetty 来源: https://codeday.me/bug/20190910/1801316.html