欢迎来到@dandelionl_的csdn博文,本文主要讲解Java web中Tomcat底层机制和Servlet的运行原理的相关知识
我是dandelionl_,一个正在为秋招和算法竞赛做准备的学生
喜欢的朋友可以关注一下,下次更新不迷路
Ps: 月亮越亮说明知识点越重要 (重要性或者难度越大)
Tomcat是一个开源的Java Web服务器,它是基于Java Servlet和JavaServer Pages(JSP)技术的。下面是关于Tomcat底层机制和Servlet运行原理的简要说明:
Tomcat底层机制:
Servlet运行原理:
在tomcat底层实现中, servlet作为容器, 实现可以理解为HashMap, 键是servlet-name值是servlet-class, 而HashMap就是一个容器, 从容器中得到一个servlet实例, 对其进行初始化, 供web使用, 调用其中的service()方法, service()方法对HTTP请求的method进行判断, 对每个相应的method都有相应的do方法, 可以使用.
不用tomcat以及servlet实现
package com.lxb.tomcat.handle;
//-*- code = utf-8 -*-
//@Time : 2023-07-20 13:22:00
//@Authors : 罗雄波
//@File : LxbRequestHandle.java
//@Software : IntelliJ IDEA
import com.lxb.tomcat.LxbTomcatV3;
import com.lxb.tomcat.http.LxbHttpRequest;
import com.lxb.tomcat.http.LxbHttpResponse;
import com.lxb.tomcat.servlet.LxbHttpServlet;
import com.lxb.tomcat.utils.WebUtils;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class LxbRequestHandle implements Runnable{
private Socket accept;
public LxbRequestHandle(Socket socket) {
this.accept = socket;
}
public void run() {
try {
LxbHttpRequest request = new LxbHttpRequest(accept);
LxbHttpResponse response = new LxbHttpResponse(accept.getOutputStream());
String uri = request.getUri();
if(WebUtils.isHtml(uri)) {
System.out.println(uri.substring(1));
String resp = WebUtils.readFile(uri.substring(1));
String responseInfo = LxbHttpResponse.respHeader + resp;
OutputStream outputStream = response.getOutputStream();
outputStream.write(responseInfo.getBytes());
outputStream.flush();
outputStream.close();
accept.close();
return;
}
String servletName = LxbTomcatV3.servletMapping.get(uri);
if(servletName == null) {
servletName = "";
}
LxbHttpServlet servlet = LxbTomcatV3.servlet.get(servletName);
if(servlet != null) {
servlet.service(request, response);
} else {
String resp = LxbHttpResponse.respHeader + "404 not found!!!";
OutputStream responseOutputStream = response.getOutputStream();
responseOutputStream.write(resp.getBytes());
responseOutputStream.flush();
responseOutputStream.close();
}
accept.close();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (accept != null) {
try {
accept.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
package com.lxb.tomcat.http;
//-*- code = utf-8 -*-
//@Time : 2023-07-20 14:59:24
//@Authors : 罗雄波
//@File : LxbHttpRequest.java
//@Software : IntelliJ IDEA
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.HashMap;
public class LxbHttpRequest {
private Socket socket;
private String method;
private String uri;
private HashMap parameterMapping = new HashMap();
public LxbHttpRequest(Socket socket) {
this.socket = socket;
try {
ParseProcess();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void ParseProcess() throws Exception {
BufferedReader reader =
new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf-8"));
String temp;
temp = reader.readLine();
// GET /cal.html HTTP/1.1
String[] request = temp.split(" ");
method = request[0];
int index = request[1].indexOf("?");
if (index == -1) {
uri = request[1];
} else {
uri = request[1].substring(0, index);
String parameterPair = request[1].substring(index + 1);
String[] parameters = parameterPair.split("&");
if (parameters[0] != null && !parameters[0].equals("")) {
for (String parameter : parameters) {
String[] split = parameter.split("=");
if(split.length == 2) {
parameterMapping.put(split[0], split[1]);
}
}
}
}
}
public String getMethod() {
return method;
}
public String getUri() {
return uri;
}
public String getParameter(String key) {
if(parameterMapping.get(key) != null) {
return parameterMapping.get(key);
} else {
return "";
}
}
@Override
public String toString() {
return "LxbHttpRequest" +
"{ method = " + method +
", uri = " + uri +
", parameter = " + parameterMapping +
"}";
}
}
package com.lxb.tomcat.http;
//-*- code = utf-8 -*-
//@Time : 2023-07-20 15:49:29
//@Authors : 罗雄波
//@File : LxbHttpResponse.java
//@Software : IntelliJ IDEA
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
public class LxbHttpResponse {
private OutputStream outputStream = null;
public static final String respHeader = "HTTP/1.1 200 OK\r\n" +
"Content-Type: text/html;charset=utf-8\r\n\r\n";
public LxbHttpResponse(OutputStream outputStream) {
this.outputStream = outputStream;
}
public OutputStream getOutputStream() {
return outputStream;
}
}
package com.lxb.tomcat;
//-*- code = utf-8 -*-
//@Time : 2023-07-20 15:37:29
//@Authors : 罗雄波
//@File : LxbTomcatV3.java
//@Software : IntelliJ IDEA
import com.lxb.tomcat.handle.LxbRequestHandle;
import com.lxb.tomcat.servlet.LxbHttpServlet;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
public class LxbTomcatV3 {
public static ConcurrentHashMap servlet =
new ConcurrentHashMap();
public static ConcurrentHashMap servletMapping =
new ConcurrentHashMap();
public static void main(String[] args) throws Exception {
LxbTomcatV3 lxbTomcatV3 = new LxbTomcatV3();
lxbTomcatV3.Init();
lxbTomcatV3.run();
}
public void run() {
try {
ServerSocket socket = new ServerSocket(8080);
while (!socket.isClosed()) {
Socket accept = socket.accept();
LxbRequestHandle requestHandle = new LxbRequestHandle(accept);
new Thread(requestHandle).start();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test
public void Init() {
String path = LxbTomcatV3.class.getResource("/").getPath();
// System.out.println(path);
// 该类的路径 /D:/NewExecllction/exicese%20code/lxb-tomcat/target/classes/com/lxb/tomcat/
// 根路径 /D:/NewExecllction/exicese%20code/lxb-tomcat/target/classes/
SAXReader saxReader = new SAXReader();
try {
Document document = saxReader.read(new File(path + "web.xml"));
// System.out.println(document);
Element rootElement = document.getRootElement();
List elements = rootElement.elements();
for (Element element : elements) {
if ("servlet".equalsIgnoreCase(element.getName())) {
Element servletName = element.element("servlet-name");
Element servletClass = element.element("servlet-class");
servlet.put(servletName.getText(), (LxbHttpServlet) Class.forName(servletClass.getText().trim()).newInstance());
} else if ("servlet-mapping".equalsIgnoreCase(element.getName())) {
Element servletName = element.element("servlet-name");
Element servletUrl = element.element("url-pattern");
servletMapping.put(servletUrl.getText(), servletName.getText());
}
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(servlet);
System.out.println(servletMapping);
}
@Test
public void test() {
String path = LxbTomcatV3.class.getResource("/").getPath();
System.out.println(path + "web.xml");
}
}
package com.lxb.tomcat.utils;
//-*- code = utf-8 -*-
//@Time : 2023-07-19 16:00:33
//@Authors : 罗雄波
//@File : WebUtils.java
//@Software : IntelliJ IDEA
import org.junit.Test;
import java.io.*;
public class WebUtils {
public static int parseInt(String strNum, int defaultVal) {
try {
return Integer.parseInt(strNum);
} catch (NumberFormatException e) {
System.out.println(strNum + "数字格式异常, 无法包装");
}
return defaultVal;
}
public static boolean isHtml(String uri) {
return uri.endsWith(".html");
}
public static String readFile(String filename) {
String path = com.lxb.tomcat.utils.WebUtils.class.getResource("/").getPath();
StringBuilder stringBuffer = new StringBuilder();
try {
System.out.println(path + filename);
BufferedReader bufferedReader = new BufferedReader(new FileReader(path + filename));
String buffer = null;
while ((buffer = bufferedReader.readLine()) != null && !buffer.equals("")) {
stringBuffer.append(buffer);
}
} catch (Exception e) {
e.printStackTrace();
}
return stringBuffer.toString();
}
}
package com.lxb.tomcat.servlet;
//-*- code = utf-8 -*-
//@Time : 2023-07-20 16:14:24
//@Authors : 罗雄波
//@File : LxbCalServlet.java
//@Software : IntelliJ IDEA
import com.lxb.tomcat.http.LxbHttpRequest;
import com.lxb.tomcat.http.LxbHttpResponse;
import com.lxb.tomcat.utils.WebUtils;
import java.io.IOException;
import java.io.OutputStream;
public class LxbCalServlet extends LxbHttpServlet {
@Override
public void doGet(LxbHttpRequest request, LxbHttpResponse response) {
doPost(request, response);
}
@Override
public void doPost(LxbHttpRequest request, LxbHttpResponse response) {
int num1 = WebUtils.parseInt(request.getParameter("num1"), 0);
int num2 = WebUtils.parseInt(request.getParameter("num2"), 0);
int result = num1 + num2;
OutputStream outputStream = response.getOutputStream();
String resp = LxbHttpResponse.respHeader + "求和: " + num1 + "+" + num2 + " = " + result + "";
try {
outputStream.write(resp.getBytes());
outputStream.flush();
outputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void init() throws Exception {
}
public void destroy() {
}
}
package com.lxb.tomcat.servlet;
//-*- code = utf-8 -*-
//@Time : 2023-07-20 16:09:43
//@Authors : 罗雄波
//@File : LxbServlet.java
//@Software : IntelliJ IDEA
import com.lxb.tomcat.http.LxbHttpRequest;
import com.lxb.tomcat.http.LxbHttpResponse;
import java.io.IOException;
public interface LxbServlet {
void init() throws Exception;
void service(LxbHttpRequest request, LxbHttpResponse response) throws IOException;
void destroy();
}
package com.lxb.tomcat.servlet;
//-*- code = utf-8 -*-
//@Time : 2023-07-20 16:11:02
//@Authors : 罗雄波
//@File : lxbHttpServlet.java
//@Software : IntelliJ IDEA
import com.lxb.tomcat.http.LxbHttpRequest;
import com.lxb.tomcat.http.LxbHttpResponse;
import java.io.IOException;
public abstract class LxbHttpServlet implements LxbServlet{
public void service(LxbHttpRequest request, LxbHttpResponse response) throws IOException {
if(request.getMethod().equals("GET")) {
this.doGet(request, response);
} else if(request.getMethod().equals("POST")) {
this.doPost(request, response);
}
}
public void doGet(LxbHttpRequest request, LxbHttpResponse response) {
}
public void doPost(LxbHttpRequest request, LxbHttpResponse response) {
}
}