---
title: "谈谈jetty response模型"
author: "helpbs"
date: "2012-03-16T16:11:00Z"
tags: []
slug: "jetty-response"
draft: false
lastmod: "2012-04-20T18:29:59Z"
id: 1492061
url: "https://helpbs.iteye.com/blog/1492061"
---

1）jetty 响应的概念模型

![](http://hi.csdn.net/attachment/201203/16/0_13318860016s9m.gif)​

- SelectChannelEndPoint： 底层的socket的封装，代表每次请求对应的网络连接（偏网路底层）
- AsyncHttpConnection：代表每次连接（偏上层一点），管理相关的request,response,HttpParser,HttpGenerator实例
- HttpParser：请求解析
- HttpGenerator：负责最终的response生成
- Response：不解释
- Request：不解释
- JettyServer: servlet容器，负责处理servlet相关逻辑

2）请求的实例化

![](http://hi.csdn.net/attachment/201203/16/0_1331886017uNw3.gif)​

- ​select线程感知到网络请求于是开始初始化途中的各个相关类的实例
- 最后将请求封装成一个endpoint实例丢入worker线程的队列中的等待处理

3）jetty 整体的响应流程

![](http://hi.csdn.net/attachment/201203/16/0_1331886033d8gT.gif)

- worker线程从请求队列获取请求
- 请求（底层是个SelectChannelEndPoint）开始处理
- SelectChannelEndPoint调用相关的AsyncHttpConnection进行处理
- AsyncHttpConnection调用HttpParser解析请求
- AsyncHttpConnection调用servlet容器处理请求（真正的业务处理）
- **servlet处理完毕处理，AsyncHttpConnection开始调用Response处理响应**

4）在servlet中调用write/flush的底层实现

样例代码：

```java
PrintWriter out = response.getWriter();
out.write(request.getParameter("id"));
out.flush();
```

![](http://hi.csdn.net/attachment/201203/16/0_1331886049ML19.gif)

- servlet中调用write底层会调用HttpGenerator的addContent方法
- addContent会将内容填充到HttpGenerator的\_content,\_content内容会被拷贝到内部buffer，如果超过内部buffer的长度就会自动flush
- servlet中调用write底层会调用HttpGenerator的flushBuffer，此操作会触发真正的网络流，下一节会具体谈

5）Response.complete到底干了什么

![](http://hi.csdn.net/attachment/201203/16/0_1331886066CU1e.gif)

- 调用AsyncHttpConnection的completeResponse
  
  - 调用HttpGenerator生成header内容
  - 调用HttpGenerator生成content内容
- 一旦reponse header和response content完成，开始flush
- 会将header buffer和content buffer传入SelectChannelEndPoint的gatheringFlush做矢量IO
- 最终还是调用底层socket完成网络响应