How Tomcat Works(三)
上文中描述的简单的服务器是不符合Servlet规范的,所以本文进一步描述一个简单的Servlet容器是怎么实现的
所以我们首先要明白Servlet接口规范,规范有不同版本,本人就先一视同仁了:
public interface Servlet { public void init(ServletConfig config) throws ServletException; public ServletConfig getServletConfig(); public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException;
public String getServletInfo(); public void destroy();
}
上面的方法中,init() 、service()和 destroy()是与Servlet的生命周期密切相关的方法,熟悉Servlet生命周期的童鞋是比较清楚的
Servlet容器通常只调用Servlet实例的init()方法一次,用于初始化相关信息;
service()方法用于响应客户端请求,传入ServletRequest和ServletResponse参数,service()方法会被多次调用
当Servlet容器关闭或Servlet容器需要释放内存时,会调用Servlet实例的destroy()方法,用于清理自身持有的资源,如内存、文件句柄和线程等,确保所有的持久化状态与内存中该Servlet对象的当前状态同步。
下面我们来看一个简单的Servlet容器怎么实现:
HttpServer1类:
public class HttpServer1 { /** WEB_ROOT is the directory where our HTML and other files reside.
* For this package, WEB_ROOT is the "webroot" directory under the working
* directory.
* The working directory is the location in the file system
* from where the java command was invoked.
*/
// shutdown command
private static final String SHUTDOWN_COMMAND = "/SHUTDOWN"; // the shutdown command received
private boolean shutdown = false; public static void main(String[] args) {
HttpServer1 server = new HttpServer1();
server.await();
} public void await() {
ServerSocket serverSocket = null;
int port = 8080;
try {
serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
}
catch (IOException e) {
e.printStackTrace();
System.exit(1);
} // Loop waiting for a request
while (!shutdown) {
Socket socket = null;
InputStream input = null;
OutputStream output = null;
try {
socket = serverSocket.accept();
input = socket.getInputStream();
output = socket.getOutputStream(); // create Request object and parse
Request request = new Request(input);
request.parse(); // create Response object
Response response = new Response(output);
response.setRequest(request); // check if this is a request for a servlet or a static resource
// a request for a servlet begins with "/servlet/"
if (request.getUri().startsWith("/servlet/")) {
ServletProcessor1 processor = new ServletProcessor1();
processor.process(request, response);
}
else {
StaticResourceProcessor processor = new StaticResourceProcessor();
processor.process(request, response);
} // Close the socket
socket.close();
//check if the previous URI is a shutdown command
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
}
上面方法中,Servlet容器根据请求的路径分发到不同的处理类进行处理,servlet请求交给ServletProcessor1类处理,静态资源交给StaticResourceProcessor类处理
注:本文中的Servlet容器跟上文相比,将响应请求的功能解耦, 由处理器类(ServletProcessor1类和StaticResourceProcessor类)来承担
Request类(注意我们这里的Request类已经实现了ServletRequest 接口,已经是按照规范来搞的了)
public class Request implements ServletRequest { private InputStream input;
private String uri; public Request(InputStream input) {
this.input = input;
} public String getUri() {
return uri;
} private String parseUri(String requestString) {
int index1, index2;
index1 = requestString.indexOf(' ');
if (index1 != -1) {
index2 = requestString.indexOf(' ', index1 + 1);
if (index2 > index1)
return requestString.substring(index1 + 1, index2);
}
return null;
} public void parse() {
// Read a set of characters from the socket
StringBuffer request = new StringBuffer(2048);
int i;
byte[] buffer = new byte[2048];
try {
i = input.read(buffer);
}
catch (IOException e) {
e.printStackTrace();
i = -1;
}
for (int j=0; j<i; j++) {
request.append((char) buffer[j]);
}
System.out.print(request.toString());
uri = parseUri(request.toString());
} /* implementation of the ServletRequest*/
public Object getAttribute(String attribute) {
return null;
}
//省略后面的代码
}
Response类(实现ServletResponse接口)
public class Response implements ServletResponse { private static final int BUFFER_SIZE = 1024;
Request request;
OutputStream output;
PrintWriter writer; public Response(OutputStream output) {
this.output = output;
} public void setRequest(Request request) {
this.request = request;
} /* This method is used to serve a static page */
public void sendStaticResource() throws IOException {
byte[] bytes = new byte[BUFFER_SIZE];
FileInputStream fis = null;
try {
/* request.getUri has been replaced by request.getRequestURI */
File file = new File(Constants.WEB_ROOT, request.getUri());
fis = new FileInputStream(file);
/*
HTTP Response = Status-Line
*(( general-header | response-header | entity-header ) CRLF)
CRLF
[ message-body ]
Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
*/
int ch = fis.read(bytes, 0, BUFFER_SIZE);
while (ch!=-1) {
output.write(bytes, 0, ch);
ch = fis.read(bytes, 0, BUFFER_SIZE);
}
}
catch (FileNotFoundException e) {
String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
"Content-Type: text/html\r\n" +
"Content-Length: 23\r\n" +
"\r\n" +
"<h1>File Not Found</h1>";
output.write(errorMessage.getBytes());
}
finally {
if (fis!=null)
fis.close();
}
}
public PrintWriter getWriter() throws IOException {
// autoflush is true, println() will flush,
// but print() will not.
writer = new PrintWriter(output, true);
return writer;
}
//省略后面的代码
}
上面实现了获取 PrintWriter对象的方法
StaticResourceProcessor类(静态资源处理)
public class StaticResourceProcessor { public void process(Request request, Response response) {
try {
response.sendStaticResource();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
方法中仅仅简单的调用了response对象的sendStaticResource()方法
ServletProcessor1类(servlet资源处理类)
public class ServletProcessor1 { public void process(Request request, Response response) { String uri = request.getUri();
String servletName = uri.substring(uri.lastIndexOf("/") + 1);
URLClassLoader loader = null; try {
// create a URLClassLoader
URL[] urls = new URL[1];
URLStreamHandler streamHandler = null;
File classPath = new File(Constants.WEB_ROOT);
// the forming of repository is taken from the createClassLoader method in
// org.apache.catalina.startup.ClassLoaderFactory
String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString() ;
// the code for forming the URL is taken from the addRepository method in
// org.apache.catalina.loader.StandardClassLoader class.
urls[0] = new URL(null, repository, streamHandler);
loader = new URLClassLoader(urls);
}
catch (IOException e) {
System.out.println(e.toString() );
}
Class myClass = null;
try {
myClass = loader.loadClass(servletName);
}
catch (ClassNotFoundException e) {
System.out.println(e.toString());
} Servlet servlet = null; try {
servlet = (Servlet) myClass.newInstance();
servlet.service((ServletRequest) request, (ServletResponse) response);
}
catch (Exception e) {
System.out.println(e.toString());
}
catch (Throwable e) {
System.out.println(e.toString());
} }
}
上面的步骤是首先根据客户端请求路径获取请求的servlet名称,然后根据servlet类路径(类载入器仓库)创建类载入器,进一步根据servlet名称载入该servlet类并实例化,最后调用该servlet的serice()方法
其中Constants类保持工作目录常量(Servlet类路径)
public class Constants {
public static final String WEB_ROOT =
System.getProperty("user.dir") + File.separator + "webroot";
}
我们继续分析,其实上面的ServletProcessor1类的process()方法是存在问题的,在下面的代码段
Servlet servlet = null; try {
servlet = (Servlet) myClass.newInstance();
servlet.service((ServletRequest) request, (ServletResponse) response);
}
catch (Exception e) {
System.out.println(e.toString());
}
catch (Throwable e) {
System.out.println(e.toString());
}
这里的Request对象与Resposne对象分别向上转型为ServletRequest实例和ServletResponse实例
如果了解这个servlet容器内部原理的servlet程序员就可以(在自己实现的serlet类中)将ServletRequest实例和 ServletResponse实例分别向下转型为真实的Request实例和Response实例,就可以调用各自的公有方法了(Request实例的 parse()方法和Response实例的sendStaticResource()方法),而servlet容器又不能将这些公有方法私有化,因为其 他外部类还要调用它们,一个比较完美的解决方法是分别为Request类和Response类创建外观类,分别为RequestFacade类与 ResponseFacade类,与前者实现共同的接口,然后保持对前者的引用,相关的接口实现方法分别调用其引用实例的方法,于是世界从此清静了
注:其实本人认为这里不应该叫做外观类,可能叫包装器类更合适吧(因为本人没听过外观类有实现共同接口的说法)
RequestFacade类
public class RequestFacade implements ServletRequest { private ServletRequest request = null; public RequestFacade(Request request) {
this.request = request;
} /* implementation of the ServletRequest*/
public Object getAttribute(String attribute) {
return request.getAttribute(attribute);
} public Enumeration getAttributeNames() {
return request.getAttributeNames();
} public String getRealPath(String path) {
return request.getRealPath(path);
}
//省略后面的代码 }
ResponseFacade类
public class ResponseFacade implements ServletResponse { private ServletResponse response;
public ResponseFacade(Response response) {
this.response = response;
} public void flushBuffer() throws IOException {
response.flushBuffer();
} public int getBufferSize() {
return response.getBufferSize();
}
//省略后面的代码
}
---------------------------------------------------------------------------
本系列How Tomcat Works系本人原创
转载请注明出处 博客园 刺猬的温驯
本人邮箱: chenying998179#163.com (#改为@)
本文链接 http://www.cnblogs.com/chenying99/p/3231637.html
How Tomcat Works(三)的更多相关文章
- How Tomcat works — 三、tomcat启动(2)
在了解了tomcat 的一些基本组件之后,学习启动过程就更容易理解了,因为启动过程就是启动各个组件. 目录 启动顺序 Bootstrap类 Catalina类 StandardServer类和Stan ...
- How Tomcat Works(十一)
本文接下来分析tomcat的类载入器,tomcat需要实现一个自定义的载入器,而不能使用系统类载入器 (1)限制serlvet访问当前运行的java虚拟机中环境变量CLASSPATH指明的路径下的所有 ...
- How Tomcat Works(十)
本文接下来分析tomcat的日志记录器,日志记录器是用来记录消息的组件,在tomcat中,日志记录器需要与某个servlet容器相关连:在org.apache.catalina.logger包下,to ...
- How Tomcat Works(九)
本文接下来描述servlet容器是怎样管理其相关组件的生命周期的,首先本人描述一下事件监听模式,也可以称为观察者模式,该模式分为以下角色 即抽象主题角色 具体主题角色 抽象观察者角色及具体观察者角色, ...
- how tomcat works 读书笔记四 tomcat的默认连接器
事实上在第三章,就已经有了连接器的样子了,只是那仅仅是一个学习工具,在这一章我们会開始分析tomcat4里面的默认连接器. 连接器 Tomcat连接器必须满足下面几个要求 1 实现org.apache ...
- how tomcat works 总结
希望各位网友在看完<<how tomcat works>>一书或者鄙人的tomcat专栏文章后再看这篇博客 这里主要是梳理各个章节的核心概念 第一章 一个简单的Web服务器 第 ...
- How Tomcat Works(二十)
要使用一个web应用程序,必须要将表示该应用程序的Context实例部署到一个host实例中.在tomcat中,context实例可以用war文件的形式来部署,也可以将整个web应用拷贝到Tomcat ...
- How Tomcat Works(十九)
本文重点关注启动tomcat时会用到的两个类,分别为Catalina类和Bootstrap类,它们都位于org.apachae.catalina.startup包下:Catalina类用于启动或关闭S ...
- 读了两章的 How Tomcat Works
周一发现了一本书.How Tomcat Works 惯例先到豆瓣搜书评.结果书评出奇的好.然后下载了PDF.从简介中看,本书的每个章节都会不断的围绕怎么建造一个Tomcat讲解.我本人比较喜欢这种造轮 ...
随机推荐
- php最新出现的函数
1. 数据过滤函数 filter_var: filter_var — Filters a variable with a specified filter 过滤的类型有: Validate filt ...
- 【转】iOS开发UI篇—iPad和iPhone开发的比较
原文网址:http://www.cnblogs.com/wendingding/p/3918007.html iOS开发UI篇—iPad和iPhone开发的比较 一.iPad简介 1.什么是iPad ...
- 【转】在Source Insight中看Python代码
原文网址:http://www.cnblogs.com/xuxm2007/archive/2010/09/02/1815695.html SI是个很强大的代码查看修改工具,以前用来看C,C++都是相当 ...
- IOS公司开发者账号申请详细教程
谈到苹果开发者账号,我们需要区分一下个人账号.公司账号和企业账号这三种,还有一种是教育账号,这个就不多说了. 个人账号:个人申请用于开发苹果app所使用的账号,仅限于个人使用,申请比较容易,$99. ...
- php.curl详解
目前为目最全的CURL中文说明了,学PHP的要好好掌握.有很多的参数.大部份都很有用.真正掌握了它和正则,一定就是个采集高手了. PHP中的CURL函数库(Client URL Library Fun ...
- 第二个UI脚本--Python+selenium之unittest+HTMLtestRunner及python的继承
前面有一篇对于常见元素的识别和操作的python自动化脚本,这一篇就接着聊下python的类继承,已经它的第三款unittest框架,和报告收集包HTMLtestRunner的应用. 还是直接上代码吧 ...
- selenium python (十三)对于分页的处理
#!/usr/bin/python# -*- coding: utf-8 -*-__author__ = 'zuoanvip' #对于web上分页的功能,一般做如下操作: #获取总页数 # ...
- LoadRunner参数数组
参数数组提供了对一类参数集中存放的机制,其中LR内置的几个函数有:lr_paramarr_idx().lr_paramarr_len().lr_paramarr_random() 同时参数数组必须满足 ...
- leetcode:Integer to Roman(整数转化为罗马数字)
Question: Given an integer, convert it to a roman numeral. Input is guaranteed to be within the rang ...
- pycharm出现乱码
1. 'gbk' codec can't encode character u'\xb8' 解决办法 import sys reload(sys)sys.setdefaultencoding('utf ...