2021SC@SDUSC
上一篇文章介绍了HTTP的主要内容,那么接下来我们就来看源代码部分。
首先,先看AsyncServlet接口。
- 基本上,它只是一个异步函数,将 HttpRequest 映射到 HttpResponse
- 开箱即用的预定义 AsyncServlet 集合(StaticServlet、BlockingServlet、RoutingServlet 等)
- 广泛支持 AsyncServlets 的功能组合。 RoutingServlet 用于构建 servlet 路由
- HTTP 路径和方法到 AsyncServlets(包括其他 RoutingServlets)的灵活映射
- 支持路径参数(如 /users/:id)和相对路径
简单来说,它是servlet 函数的接口,异步接收 HttpRequest,处理它,然后返回 HttpResponse。
public interface AsyncServlet {
@NotNull Promisable<HttpResponse> serve(@NotNull HttpRequest request) throws Exception;
default @NotNull Promise<HttpResponse> serveAsync(@NotNull HttpRequest request) throws Exception {
return serve(request).promise();
}
static @NotNull AsyncServlet ofBlocking(@NotNull Executor executor, @NotNull BlockingServlet blockingServlet) {
return request -> request.loadBody()
.then(() -> Promise.ofBlocking(executor,
() -> blockingServlet.serve(request)));
}
}
方法ofBlocking()使用给定的 Executor 将给定的 BlockingServlet 包装成异步的。
BlockingServlet
AsyncServlet 的阻塞版本。
public interface BlockingServlet {
@NotNull HttpResponse serve(@NotNull HttpRequest request) throws Exception;
}
HttpExceptionFormatter
这是用于 HTTP 的格式化程序功能的接口。它转换可能从服务器根部 servlet 返回的未处理的检查异常,并将它们转换为 HTTP 错误响应。其具有如下操作:
标准格式化程序将除 HttpException 之外的所有异常映射到具有 500 状态代码的空响应。 HttpExceptions 被映射到响应及其状态代码、消息和原因的堆栈跟踪(如果已指定)。
HttpExceptionFormatter DEFAULT_FORMATTER = e -> {
Ht