好久没有写博客了,最近要毕业了,写论文写的好烦。然后就又拿起了这本《深入剖析tomcat》来看一看。 哎,希望今年能顺利毕业。
其实本篇也就是对《深入理解tomcat》中第二章第一个简单的servlet容器的代码进行分析。
一、简单Servlet容器的功能
本篇所构建的Servlet功能如下:
1,解析请求的url,将url封装成一个自定义的Request。解析包括对请求服务器资源名称的解析。
2,接收浏览器的请求,根据请求的URL的类型。选择是加载一个Servlet类还是返回系统的静态文件。当URL中包含/servlet/关键路径时,加载指定的Servlet,当不包含时,加载静态文件。
3,若加载的是Servlet调用该Servlet的service()方法,当是静态文件的时候,直接返回文件。在传输完成后,关闭socket
二、系统类简介
- HttpServer1:程序启动的总入口
- Request :在接收到浏览器请求时,HttpServer1利用Request将请求进行包装
- Response:对浏览器的回应封装
- StaticResourceProcessor:处理静态资源的类
- ServletProcessor1:处理请求是Servlet时的类
- Constants:系统常量
三、代码结构
在src目录下,建立ex02.pyrmont包。同时在src同级目录下建立webroot目录,里面包含一个index.html静态资源以及一个编译好的Servlet。
三、源码解析
1,HttpServer1.java
package ex02.pyrmont;
import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class HttpServer1 {
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);
}
while (!shutdown) {
Socket socket = null;
InputStream input = null;
OutputStream output = null;
try {
socket = serverSocket.accept();
input = socket.getInputStream();
output = socket.getOutputStream();
// 将浏览器的请求封装成一个自定义的Request
Request request = new Request(input);
request.parse();
// 建立一个相应类
Response response = new Response(output);
response.setRequest(request);
// 通过上面Request解析后的URl判断该URI中是否包含“/servlet/”路径,如果有,调用ServletProcessor1类相应
//浏览器,如果没有,调用StaticResourceProcessor相应浏览器
if (request.getUri().startsWith("/servlet/")) {
ServletProcessor1 processor = new ServletProcessor1();
processor.process(request, response);
}
else {
StaticResourceProcessor processor = new StaticResourceProcessor();
processor.process(request, response);
}
// 在回复浏览器后,关闭与浏览器产生联系的套接字
socket.close();
//判断一下浏览器指令是否为关闭服务器
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
}
在HttpServer1中启动后,主要是调用await()方法,在该方法中建立一个serverSocket。用来监控本地的8080端口,在接收到浏览器的请求后,创建Request对象将浏览器请求封装。然后通过请求的URL判断是请求的静态文件还是Servlet。最后关闭socket。
2,Request.java 源码如下
package ex02.pyrmont;
import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.*;
public class Request implements ServletRequest {
private InputStream input;
private String uri;
public Request(InputStream input) {
this.input = input;
}
public String getUri() {
return uri;
}
// 解析传递过来的URI,形如: GET /servlet/PrimitiveServlet HTTP/1.1
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;
}
// 从建立的socket中获取浏览器传送过来的信息,其实就是tomcat4源码剖析(一)中讲到的一般请求过程
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]);
}
// request中就是浏览器传递过来的东西
System.out.print(request.toString());
uri = parseUri(request.toString()); // 解析浏览器传递过来的URI
}
//之后添加的是继承ServletRequest需要实现的方法,暂时不需要管
/* implementation of the ServletRequest*/
public Object getAttribute(String attribute) {
return null;
}
public Enumeration getAttributeNames() {
return null;
}
public String getRealPath(String path) {
return null;
}
public RequestDispatcher getRequestDispatcher(String path) {
return null;
}
public boolean isSecure() {
return false;
}
public String getCharacterEncoding() {
return null;
}
public int getContentLength() {
return 0;
}
public String getContentType() {
return null;
}
public ServletInputStream getInputStream() throws IOException {
return null;
}
public Locale getLocale() {
return null;
}
public Enumeration getLocales() {
return null;
}
public String getParameter(String name) {
return null;
}
public Map getParameterMap() {
return null;
}
public Enumeration getParameterNames() {
return null;
}
public String[] getParameterValues(String parameter) {
return null;
}
public String getProtocol() {
return null;
}
public BufferedReader getReader() throws IOException {
return null;
}
public String getRemoteAddr() {
return null;
}
public String getRemoteHost() {
return null;
}
public String getScheme() {
return null;
}
public String getServerName() {
return null;
}
public int getServerPort() {
return 0;
}
public void removeAttribute(String attribute) {
}
public void setAttribute(String key, Object value) {
}
public void setCharacterEncoding(String encoding)
throws UnsupportedEncodingException {
}
@Override
public long getContentLengthLong() {
return 0;
}
@Override
public int getRemotePort() {
return 0;
}
@Override
public String getLocalName() {
return null;
}
@Override
public String getLocalAddr() {
return null;
}
@Override
public int getLocalPort() {
return 0;
}
@Override
public ServletContext getServletContext() {
return null;
}
@Override
public AsyncContext startAsync() throws IllegalStateException {
return null;
}
@Override
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException {
return null;
}
@Override
public boolean isAsyncStarted() {
return false;
}
@Override
public boolean isAsyncSupported() {
return false;
}
@Override
public AsyncContext getAsyncContext() {
return null;
}
@Override
public DispatcherType getDispatcherType() {
return null;
}
}
在Request类中,主要就做了一件事将如下字符串进行解析,并将其中的URI赋值给Request类中的uri变量。
GET /servlet/PrimitiveServlet HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9,en;q=0.8
3, Response.java
package ex02.pyrmont;
import java.io.OutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.PrintWriter;
import java.util.Locale;
import javax.servlet.ServletResponse;
import javax.servlet.ServletOutputStream;
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();
}
}
/** implementation of ServletResponse */
public void flushBuffer() throws IOException {
}
public int getBufferSize() {
return 0;
}
public String getCharacterEncoding() {
return null;
}
public Locale getLocale() {
return null;
}
public ServletOutputStream getOutputStream() throws IOException {
return null;
}
public PrintWriter getWriter() throws IOException {
// autoflush is true, println() will flush,
// but print() will not.
writer = new PrintWriter(output, true);
return writer;
}
public boolean isCommitted() {
return false;
}
public void reset() {
}
public void resetBuffer() {
}
public void setBufferSize(int size) {
}
public void setContentLength(int length) {
}
public void setContentType(String type) {
}
public void setLocale(Locale locale) {
}
public String getContentType() {
return null;
}
public void setCharacterEncoding(String s) {
}
public void setContentLengthLong(long l) {
}
}
Response类中最主要的就是sendStaticResource()方法,主要是在根据浏览器请求的是静态文件时,供StaticResourceProcessor类调用。在查找静态资源时,如果没有找到,则返回404页面。
4,ServletProcessor1.java
package ex02.pyrmont;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;
import java.io.File;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class ServletProcessor1 {
public void process(Request request, Response response) {
String uri = request.getUri();
String servletName = uri.substring(uri.lastIndexOf("/") + 1); //找到具体所要请求的servlet名字
URLClassLoader loader = null; //类加载器
try {
// 创建类加载器
URL[] urls = new URL[1];
URLStreamHandler streamHandler = null;
File classPath = new File(Constants.WEB_ROOT);
String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString() ;
urls[0] = new URL(null, repository, streamHandler);
loader = new URLClassLoader(urls);
}
catch (IOException e) {
System.out.println(e.toString() );
}
Class myClass = null;
try {
//加载相应的servlet.class文件
myClass = loader.loadClass(servletName);
}
catch (ClassNotFoundException e) {
System.out.println(e.toString());
}
Servlet servlet = null;
try {
// 创建Servlet实例
servlet = (Servlet) myClass.newInstance();
// 调用Servlet的service()方法
servlet.service((ServletRequest) request, (ServletResponse) response);
}
catch (Exception e) {
System.out.println(e.toString());
}
catch (Throwable e) {
System.out.println(e.toString());
}
}
}
ServletProcessor1的主要作用是根据指定的servlet名称找到对应的资源利用反射创建对应的servlet实例。然后调用实例的service()方法。
5,StaticResourceProcessor.java
package ex02.pyrmont;
import java.io.IOException;
public class StaticResourceProcessor {
public void process(Request request, Response response) {
try {
response.sendStaticResource();// 调用response的静态方法
}
catch (IOException e) {
e.printStackTrace();
}
}
}
6,Constants.java
package ex02.pyrmont;
import java.io.File;
public class Constants {
public static final String WEB_ROOT =
System.getProperty("user.dir") + File.separator + "webroot";
}
WEB_ROOT 在本机上就是D:\F\IDEA程序\Tomcat\webroot路径。
6,PrimitiveServlet.java
import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;
public class PrimitiveServlet implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
PrintWriter out = servletResponse.getWriter();
out.println("HTTP/1.1 200 OK"); // 记住一定要加上这一句哦
out.println("Server: zkw");
out.println();
out.println("<html>");
out.println("Learning how tomcat works");
out.println("</html>");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}
7,index.html
HTTP/1.1 200 OK
Date: Fri, 22 May 2009 06:07:21 GMT
Content-Type: text/html; charset=UTF-8
<html>
<head>
<title>Welcome to BrainySoftware</title>
</head>
<body>
<br>
Welcome to BrainySoftware.
</body>
</html>
注意要加上前面的三行。
四、其他
1,运行
在浏览器输入
http://localhost:8080/servlet/PrimitiveServlet 之后,出现如下图片
在浏览器输入http://localhost:8080/index.html 后出现如下图片
2 建议
第三节中代码为完整代码,可以直接复制到自己工程项目中运行。同时也上传了项目的完整代码,下载地址:https://download.youkuaiyun.com/download/tyoukai_/11019831
建议自己跑一下,以调试的模式,单步看看程序执行结果。
以上就是最简单的Servlet容器了。Tomcat在此基础上进行了很多扩展,但是原理都是一样的。