手写web server: 3-Servlet

217 阅读1分钟

【声明】文章为本人学习时记录的笔记。 原课程地址:www.liaoxuefeng.com/wiki/154595…

上一篇中是使用了HttpExchange来处理http的请求与响应。而Servlet处理HTTP的接口是基于HttpServletRequestHttpServletResponse。那么我们如何将HttpExchange转换为request和response的操作?

【tag】适配器模式 image.png

接口HttpExchangeRequestHttpExchangeResponseHttpExchange的关于request和response的操作分开定义。

image.png

在实现servlet规范下的HttpServletRequestHttpServletResponse时,通过成员变量的方式使用HttpExchangeRequestHttpExchangeResponse

    
    @Override
    public void handle(HttpExchange exchange) throws IOException {
        logger.info("{}: {}?{}", exchange.getRequestMethod(), exchange.getRequestURI().getPath(), exchange.getRequestURI().getRawQuery());
        var adapter = new HttpExchangeAdapter(exchange);
        var request = new HttpServletRequestImpl(adapter);
        var response = new HttpServletResponseImpl(adapter);
        // process:
        try {
            process(request, response);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

然后在Connector中处理HttpExchange消息时,就可以将request和response分别交给HttpServletRequestImplHttpServletResponseImpl进行处理。