Jetty的架构(翻译)
Jetty的架构
Connector(连接器)集合负责接收HTTP连接。handler(处理器)集合负责处理连接请求并给予响应。而Jetty Server(服务器)则是前两者的管道连接器。负责创建并初始化connector、handler、ThreadPool组件,然后调用start方法启动他们。ThreadPool(线程池)为他们完成工作提供线程。
Jetty Server演示代码
jetty遵循一些比较规范的模式,最抽象的概念通过接口定义,如连接器,处理器和缓冲区。在抽象类中实现这些接口的通用操作,如AbstractConnector, AbstractHandler and AbstractBuffer。
?
连接器表示协议的处理者,负责解析请求并生成响应。不同类型的连接器在其基于的协议下有效,如调度模型和IO API的使用:
?SocketConnector - for few busy connections or when NIO is not available.
?BlockingChannelConnector - for few busy connections when NIO is available
?SelectChannelConnector - for many mostly idle connections or asynchronous handling of Ajax requests.
?SslSocketConnector - 没有使用NIO的SSL连接器。
?SslSelectChannelConnector - 使用非阻塞NIO支持的SSL连接器。
?AJPConnector AJP protocol support for connections from apache mod_jk or mod_proxy_ajp
connectors的使用代码
Connector connector=new SelectChannelConnector();connector.setPort(8080);HandlersHandler组件负责处理接收到的请求. handler核心的API是handle方法:
?
public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException;?这个方法的实现可以处理请求,传递请求到另外一个处理器(或者servlet),或修改并包装请求并传递出去。有三种类型的处理器:
- Coordinating Handlers - 负责路由请求到其他处理器的处理器(eg HandlerCollection, ContextHandlerCollection) Filtering Handlers - 负责增加请求并传递到其他处理器的处理器(eg. HandlerWrapper, ContextHandler, SessionHandler) Generating Handlers - 负责产生内容的处理器(eg ResourceHandler and ServletHandler)
Handler代码如下
Handler handler=new HelloHandler();server.setHandler(handler); public static class HelloHandler extends AbstractHandler { public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException { Request base_request = (request instanceof Request) ? (Request)request:HttpConnection.getCurrentConnection().getRequest(); base_request.setHandled(true); response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("<h1>Hello OneHandler</h1>"); } }?ServletsContextContexts是一种处理器,负责组织其他特定URI上下文路径或者一个虚拟机的处理器。通常情况下一个上下文必须有:
一个上下文路径,负责通过上下文定义哪一个请求被处理。 (eg /myapp ) 一个基于静态内容的资源(a docroot) 一个类加载器去获得指定上下文中的类(通常在docroot/WEB-INF/classes下) 虚拟机名称上下文实现包括:
?ContextHandler Servlet Context ?a Web Application ContextContext示意代码:
ContextHandler context = new ContextHandler();context.setContextPath("/");context.setResourceBase(".");context.setClassLoader(Thread.currentThread().getContextClassLoader());server.setHandler(context);?Web Applications
一个WebAppContext是servlet Context的子类,它提供web应用程序标准的层次结构,以及session, security, listeners, filter, servlets 和JSP的配置。