您的位置:首页 > 运维架构 > Tomcat

How Tomcat Works之(可接受servlet请求)

2017-08-07 23:23 344 查看
一、环境

1、在上个项目中新建一个ex02包,并在此包下新建两个包分别为one,two。这里要模拟两种形式。

二、编码

1、在pom文件下新添一下内容

<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
</dependencies>


2、既然是接受servlet请求,那必须要有servlet类,所以我们编写一个servlet类,实现他的接口,只在init和destory以及service中有具体的实现,其他都是空方法体,具体如下。他在ex02包下。

package ex02;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
* Created with IntelliJ IDEA.
* Description:
* 段浩杰   2017-08-07-20:15
*/
public class MyServlet implements Servlet {
public void init(ServletConfig servletConfig) throws ServletException {
System.out.println("init");
}

public ServletConfig getServletConfig() {
return null;
}

public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("from service");
PrintWriter printWriter = servletResponse.getWriter();
printWriter.println("Hello Roses are red");
printWriter.print("Violets are blue");
}

public String getServletInfo() {
return null;
}

public void destroy() {
System.out.println("destory");
}
}


3、然后编写一个常量类,可以理解成就是配置文件,这里为了简单。在ex02/one包下

package ex02.one;

import java.io.File;

public class Constants {
public static final String WEB_ROOT =
System.getProperty("user.dir") + File.separator + "webroot";

public static final String CLASS_PACKAGE = "ex02.";

public static final String SERVLET_ROOT =
System.getProperty("user.dir") + File.separator + "target\\classes\\ex02";

}


4、编写Request对象,用来解析请求体,解析请求地址。和上一个基本一样,无非实现了ServletRequest接口,其他不变,方法都是空方法。

package ex02.one;

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 {
public int getRemotePort() {
return 0;
}

public String getLocalName() {
return null;
}

public String getLocalAddr() {
return null;
}

public int getLocalPort() {
return 0;
}

public ServletContext getServletContext() {
return null;
}

public AsyncContext startAsy
4000
nc() throws IllegalStateException {
return null;
}

public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException {
return null;
}

public boolean isAsyncStarted() {
return false;
}

public boolean isAsyncSupported() {
return false;
}

public AsyncContext getAsyncContext() {
return null;
}

public DispatcherType getDispatcherType() {
return null;
}

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;
}

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 {
}

}


5、之后编写Response,内容和上一个的Response基本一样,多实现了ServletResponse接口,对响应资源的包装。

package ex02.one;

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 {
public String getContentType() {
return null;
}

public void setCharacterEncoding(String s) {

}

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) {
}
}


6、然后编写StaticResourceProcessor
1021d
负责静态资源的请求

package ex02.one;

import java.io.IOException;

public class StaticResourceProcessor {

public void process(Request request, Response response) {
try {
response.sendStaticResource();
}
catch (IOException e) {
e.printStackTrace();
}
}
}


7、ServletProcessor1负责servlet的请求,通过request找到需要加载的类,然后通过classloader进行动态初始化,调用对应的service方法,来完成响应。

package ex02.one;

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);
URLClassLoader loader = null;
try {
// create a URLClassLoader
URL[] urls = new URL[1];
URLStreamHandler streamHandler = null;
File classPath = new File(Constants.SERVLET_ROOT);
// the forming of repository is taken from the createClassLoader method in
// 找到类的名字
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(Constants.CLASS_PACKAGE+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());
}
}
}


8、服务器启动类,同时也是判断是静态请求还是servlet请求的路由器。

package ex02.one;

import java.net.Socket;
import java.net.ServerSocket;
import java.net.InetAddress;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

/**
* 服务器  和第一个相比多了
* 1、判断是那种请求
* 2、对不同请求不同处理
*/
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.
*/
// shoutdown命令
private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";

//
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 = new Request(input);
request.parse();

// 创建响应对象
Response response = new Response(output);
response.setRequest(request);

//检查时servlet还是静态资源
// servilet是以 "/servlet/"开始
if (request.getUri().startsWith("/servlet/")) {
ServletProcessor1 processor = new ServletProcessor1();
processor.process(request, response);
} else {
StaticResourceProcessor processor = new StaticResourceProcessor();
processor.process(request, response);
}

// 关闭socket
socket.close();
//检查url是否符合关闭命令
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
}


9、启动服务器,在ie浏览器下输入

http://127.0.0.1:8080/servlet/MyServlet


效果如图



若输入

http://127.0.0.1:8080/index.html


效果如图



10、源码地址

https://gitee.com/lgr123/tomcat/tree/master/


11、总结

通过此项目可以知道,当一个请求道服务器端,服务器都会做什吗?

(1)接收请求,初始化request和response

(2)判断是什么请求

(3)如果是servlet请求,那么交给servlet请求的处理类

(4)servlet处理类会在request中读取需要初始化的servlet类,进行处理请求。

(5)如果是静态资源请求,那么交给静态资源处理类。

(6)静态资源处理类,来加载静态资源信息并封装的response中,来进行响应。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  tomcat servlet