【声明】文章为本人学习时记录的笔记。 原课程地址:www.liaoxuefeng.com/wiki/154595…
上一篇中是使用了HttpExchange来处理http的请求与响应。而Servlet处理HTTP的接口是基于HttpServletRequest和HttpServletResponse。那么我们如何将HttpExchange转换为request和response的操作?
【tag】适配器模式
接口HttpExchangeRequest和HttpExchangeResponse将HttpExchange的关于request和response的操作分开定义。
在实现servlet规范下的HttpServletRequest和HttpServletResponse时,通过成员变量的方式使用HttpExchangeRequest和HttpExchangeResponse。
@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分别交给HttpServletRequestImpl和HttpServletResponseImpl进行处理。