tomcat解析漏洞_-【9.Tomcat底层剖析与性能优化】7、自定义tomcat - + request

📅 2026-11-30 👤 拼多多助力营销技巧 📂 手赚APP 👁️ 218 次阅读

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */

#content_views .toc,

/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */

#content_views.markdown_views > p:empty:has(+ .toc),

#content_views.markdown_views > .toc + p:empty,

/* 富文本旧版目录标记 */

#content_views.htmledit_views #main-toc,

#content_views.htmledit_views #hr-toc,

#content_views.htmledit_views p[id*="-toc"] {

display: none !important;

}

/* 目录去掉后,紧跟的首个标题不再多出一块上边距 */

#content_views.markdown_views > .toc + h1,

#content_views.markdown_views > .toc + h2,

#content_views.markdown_views > .toc + h3,

#content_views.markdown_views > .toc + h4,

#content_views.markdown_views > .toc + p:empty + h1,

#content_views.markdown_views > .toc + p:empty + h2,

#content_views.markdown_views > .toc + p:empty + h3,

#content_views.markdown_views > .toc + p:empty + h4 {

margin-top: 0 !important;

}

自定义Tomcat - CodingTomcat 详细实现步骤

下面我将详细说明每个步骤的实现细节和源代码,确保每一步都有清晰的说明。

步骤1:创建项目结构和基础类

说明

首先我们需要创建项目的基本结构,包括包结构和必要的类文件。这个结构将帮助我们组织代码,使其更易于维护和扩展。

实现

创建以下目录结构:

CodingTomcat/

│

├── src/

│ ├── com/

│ │ └── codingtomcat/

│ │ ├── CodingTomcat.java

│ │ ├── Request.java

│ │ ├── Response.java

│ │ ├── Servlet.java

│ │ ├── StaticResourceProcessor.java

│ │ ├── ServletProcessor.java

│ │ └── RequestProcessor.java

│ │

│ └── HelloServlet.java

│

└── webapps/

├── index.html

├── style.css

└── ...

步骤2:实现主类 CodingTomcat

说明

CodingTomcat 类是服务器的主入口点,负责:

初始化服务器配置创建线程池处理并发请求监听指定端口接收客户端连接加载Servlet映射配置启动和停止服务器

源代码

package com.codingtomcat;

import java.io.IOException;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.HashMap;

import java.util.Map;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

public class CodingTomcat {

private static final int PORT = 8080;

private static final int THREAD_POOL_SIZE = 10;

private ExecutorService threadPool;

private ServerSocket serverSocket;

private boolean shutdown = false;

// Servlet映射表,存储URL路径到Servlet类的映射

private MapservletMapping = new HashMap<>();

public static void main(String[] args) {

CodingTomcat tomcat = new CodingTomcat();

tomcat.start();

}

public void start() {

try {

// 初始化线程池,用于处理并发请求

threadPool = Executors.newFixedThreadPool(THREAD_POOL_SIZE);

// 加载Servlet配置

loadServletMapping();

// 创建服务器套接字,监听指定端口

serverSocket = new ServerSocket(PORT);

System.out.println("CodingTomcat started on port " + PORT);

// 主循环,等待客户端连接

while (!shutdown) {

// 接受客户端连接

Socket socket = serverSocket.accept();

System.out.println("New connection from: " + socket.getInetAddress());

// 为每个连接创建任务并提交到线程池

threadPool.execute(new RequestProcessor(socket, servletMapping));

}

} catch (IOException e) {

e.printStackTrace();

} finally {

stop();

}

}

public void stop() {

shutdown = true;

if (threadPool != null) {

threadPool.shutdown();

}

try {

if (serverSocket != null) {

serverSocket.close();

}

} catch (IOException e) {

e.printStackTrace();

}

System.out.println("CodingTomcat stopped");

}

// 加载Servlet映射(简化版,实际应从配置文件中读取)

private void loadServletMapping() {

servletMapping.put("/hello", "HelloServlet");

// 可以添加更多映射

System.out.println("Loaded servlet mapping: " + servletMapping);

}

}

步骤3:实现请求封装类 Request

说明

Request 类负责解析HTTP请求,提取以下信息:

请求方法(GET、POST等)请求URI和路径查询参数请求头信息

源代码

package com.codingtomcat;

import java.io.IOException;

import java.io.InputStream;

import java.util.HashMap;

import java.util.Map;

import java.util.StringTokenizer;

public class Request {

private InputStream input;

private String uri;

private String method;

private String path;

private Mapparameters = new HashMap<>();

private Mapheaders = new HashMap<>();

public Request(InputStream input) {

this.input = input;

}

public void parse() {

try {

// 读取输入流

StringBuilder request = new StringBuilder(2048);

byte[] buffer = new byte[2048];

int i = input.read(buffer);

for (int j = 0; j < i; j++) {

request.append((char) buffer[j]);

}

System.out.println("Received request: " + request.toString());

// 解析请求方法

method = parseMethod(request.toString());

// 解析URI

uri = parseUri(request.toString());

// 解析路径和参数

int questionMarkIndex = uri.indexOf('?');

if (questionMarkIndex >= 0) {

path = uri.substring(0, questionMarkIndex);

String paramsString = uri.substring(questionMarkIndex + 1);

parseParameters(paramsString);

} else {

path = uri;

}

// 解析请求头

parseHeaders(request.toString());

System.out.println("Parsed request: method=" + method + ", uri=" + uri +

", path=" + path + ", parameters=" + parameters);

} catch (IOException e) {

e.printStackTrace();

}

}

private String parseMethod(String requestString) {

int index = requestString.indexOf(' ');

if (index != -1) {

return requestString.substring(0, index);

}

return "";

}

private String parseUri(String requestString) {

int index1 = requestString.indexOf(' ');

if (index1 != -1) {

int index2 = requestString.indexOf(' ', index1 + 1);

if (index2 > index1) {

return requestString.substring(index1 + 1, index2);

}

}

return "";

}

private void parseParameters(String paramsString) {

StringTokenizer tokenizer = new StringTokenizer(paramsString, "&");

while (tokenizer.hasMoreTokens()) {

String token = tokenizer.nextToken();

int equalsIndex = token.indexOf('=');

if (equalsIndex >= 0) {

String name = token.substring(0, equalsIndex);

String value = token.substring(equalsIndex + 1);

parameters.put(name, value);

}

}

}

private void parseHeaders(String requestString) {

String[] lines = requestString.split("\r\n");

for (int i = 1; i < lines.length; i++) {

String line = lines[i];

if (line.isEmpty()) break; // 空行表示头部结束

int colonIndex = line.indexOf(':');

if (colonIndex > 0) {

String name = line.substring(0, colonIndex).trim();

String value = line.substring(colonIndex + 1).trim();

headers.put(name, value);

}

}

}

// Getter方法

public String getUri() { return uri; }

public String getMethod() { return method; }

public String getPath() { return path; }

public String getParameter(String name) { return parameters.get(name); }

public String getHeader(String name) { return headers.get(name); }

}

步骤4:实现响应封装类 Response

说明

Response 类负责生成HTTP响应,包括:

处理静态资源请求设置HTTP响应头发送响应内容给客户端根据文件扩展名确定内容类型

源代码

package com.codingtomcat;

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.OutputStream;

public class Response {

private OutputStream output;

private Request request;

private static final int BUFFER_SIZE = 1024;

public Response(OutputStream output) {

this.output = output;

}

public void setRequest(Request request) {

this.request = request;

}

public void sendStaticResource() throws IOException {

byte[] bytes = new byte[BUFFER_SIZE];

FileInputStream fis = null;

try {

// 构建文件路径,从webapps目录查找文件

File file = new File("webapps", request.getPath());

// 处理默认页面请求

if (file.isDirectory()) {

file = new File(file, "index.html");

}

if (file.exists() && !file.isDirectory()) {

fis = new FileInputStream(file);

// 构建HTTP响应头

String contentType = getContentType(request.getPath());

String header = "HTTP/1.1 200 OK\r\n" +

"Content-Type: " + contentType + "\r\n" +

"Content-Length: " + file.length() + "\r\n" +

"\r\n";

output.write(header.getBytes());

// 发送文件内容

int ch = fis.read(bytes, 0, BUFFER_SIZE);

while (ch != -1) {

output.write(bytes, 0, ch);

ch = fis.read(bytes, 0, BUFFER_SIZE);

}

System.out.println("Served static resource: " + file.getPath());

} else {

// 文件不存在,返回404

String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +

"Content-Type: text/html\r\n" +

"Content-Length: 23\r\n" +

"\r\n" +

"

404 Not Found";

output.write(errorMessage.getBytes());

System.out.println("Resource not found: " + file.getPath());

}

} finally {

if (fis != null) {

fis.close();

}

}

}

// 根据文件扩展名获取内容类型

private String getContentType(String path) {

if (path.endsWith(".html") || path.endsWith(".htm")) {

return "text/html";

} else if (path.endsWith(".css")) {

return "text/css";

} else if (path.endsWith(".js")) {

return "application/javascript";

} else if (path.endsWith(".jpg") || path.endsWith(".jpeg")) {

return "image/jpeg";

} else if (path.endsWith(".png")) {

return "image/png";

} else if (path.endsWith(".gif")) {

return "image/gif";

} else if (path.endsWith(".ico")) {

return "image/x-icon";

} else {

return "application/octet-stream";

}

}

// 用于动态资源输出响应

public OutputStream getOutput() {

return output;

}

// 设置响应头

public void setHeader(String name, String value) throws IOException {

output.write((name + ": " + value + "\r\n").getBytes());

}

}

步骤5:实现Servlet接口

说明

Servlet 接口定义了动态资源处理的标准方法,所有自定义Servlet都需要实现这个接口。它遵循了Servlet规范的基本生命周期。

源代码

package com.codingtomcat;

public interface Servlet {

// 初始化方法,在Servlet实例化后调用

void init() throws Exception;

// 处理请求的核心方法

void service(Request request, Response response) throws Exception;

// 销毁方法,在Servlet被移除前调用

void destroy();

}

步骤6:实现静态资源处理器

说明

StaticResourceProcessor 类负责处理静态资源请求,如HTML、CSS、JavaScript和图像文件。它使用Response类的sendStaticResource方法来发送文件内容。

源代码

package com.codingtomcat;

public class StaticResourceProcessor {

public void process(Request request, Response response) {

try {

System.out.println("Processing static resource: " + request.getPath());

response.sendStaticResource();

} catch (Exception e) {

e.printStackTrace();

try {

// 发送500错误响应

String errorMessage = "HTTP/1.1 500 Internal Server Error\r\n" +

"Content-Type: text/html\r\n" +

"Content-Length: 31\r\n" +

"\r\n" +

"

500 Internal Server Error";

response.getOutput().write(errorMessage.getBytes());

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

}

步骤7:实现动态资源处理器

说明

ServletProcessor 类负责处理动态资源请求,它:

根据URL路径查找对应的Servlet类使用反射机制实例化Servlet调用Servlet的生命周期方法(init, service, destroy)处理异常情况

源代码

package com.codingtomcat; 拼多多帮助力入口

import java.util.Map;

public class ServletProcessor {

public void process(Request request, Response response, MapservletMapping) {

try {

String servletName = servletMapping.get(request.getPath());

if (servletName != null) {

System.out.println("Processing servlet: " + servletName);

// 使用反射加载Servlet类

Class servletClass = Class.forName(servletName);

Servlet servlet = (Servlet) servletClass.newInstance();

// 初始化Servlet

servlet.init();

// 调用service方法处理请求

servlet.service(request, response);

// 销毁Servlet

servlet.destroy();

} else {

// 没有找到对应的Servlet

String errorMessage = "HTTP/1.1 404 Servlet Not Found\r\n" +

"Content-Type: text/html\r\n" +

"Content-Length: 26\r\n" +

"\r\n" +

"

404 Servlet Not Found";

response.getOutput().write(errorMessage.getBytes());

System.out.println("Servlet not found for path: " + request.getPath());

}

} catch (Exception e) {

e.printStackTrace();

try {

// 发送500错误响应

String errorMessage = "HTTP/1.1 500 Internal Server Error\r\n" +

"Content-Type: text/html\r\n" +

"Content-Length: 31\r\n" +

"\r\n" +

"

500 Internal Server Error";

response.getOutput().write(errorMessage.getBytes());

} catch (IOException ex) {

ex.printStackTrace();

}

}

}

}

步骤8:实现请求处理线程

说明

RequestProcessor 类实现了Runnable接口,每个客户端连接都会创建一个实例并在单独的线程中执行。它负责:

解析HTTP请求创建响应对象根据请求类型分发给相应的处理器(静态或动态)关闭连接

源代码

package com.codingtomcat;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.Socket;

import java.util.Map;

public class RequestProcessor implements Runnable {

private Socket socket;

private MapservletMapping;

public RequestProcessor(Socket socket, MapservletMapping) {

this.socket = socket;

this.servletMapping = servletMapping;

}

@Override

public void run() {

try {

// 获取输入输出流

InputStream input = socket.getInputStream();

OutputStream output = socket.getOutputStream();

// 解析请求

Request request = new Request(input);

request.parse();

// 创建响应对象

Response response = new Response(output);

response.setRequest(request);

// 判断是静态资源还是Servlet

if (servletMapping.containsKey(request.getPath())) {

// 动态资源处理

ServletProcessor processor = new ServletProcessor();

processor.process(request, response, servletMapping);

} else {

// 静态资源处理

StaticResourceProcessor processor = new StaticResourceProcessor();

processor.process(request, response);

}

// 关闭连接

socket.close();

System.out.println("Connection closed: " + socket.getInetAddress());

} catch (IOException e) {

e.printStackTrace();

}

}

}

步骤9:创建示例Servlet

说明

HelloServlet 是一个示例Servlet,演示了如何实现Servlet接口来处理动态请求。它接收一个名为"name"的参数,并返回个性化的问候语。

源代码

import com.codingtomcat.Request;

import com.codingtomcat.Response;

import com.codingtomcat.Servlet;

import java.io.IOException;

public class HelloServlet implements Servlet {

@Override

public void init() throws Exception {

System.out.println("HelloServlet initialized");

}

@Override

public void service(Request request, Response response) throws Exception {

// 生成动态内容

String name = request.getParameter("name");

if (name == null) name = "Guest";

String content = "" +

"" +

"Hello Servlet" +

"" +

"" +

"" +

"

Hello, " + name + "!" +

"

Welcome to CodingTomcat

" +

"

This is a dynamic response generated by HelloServlet

" +

"

" +

"";

// 发送响应

response.getOutput().write(("HTTP/1.1 200 OK\r\n").getBytes());

response.getOutput().write(("Content-Type: text/html\r\n").getBytes());

response.getOutput().write(("Content-Length: " + content.length() + "\r\n").getBytes());

response.getOutput().write("\r\n".getBytes());

response.getOutput().write(content.getBytes());

System.out.println("HelloServlet processed request for name: " + name);

}

@Override

public void destroy() {

System.out.println("HelloServlet destroyed");

}

}

步骤10:编译和运行

说明

这一步详细说明了如何编译和运行CodingTomcat,以及如何测试其功能。

实现步骤

创建webapps目录并添加静态资源文件: mkdir -p webapps

创建index.html文件:

Welcome to CodingTomcat

编译所有Java文件: javac -d bin src/com/codingtomcat/*.java src/HelloServlet.java

运行CodingTomcat: java -cp bin com.codingtomcat.CodingTomcat

测试访问:

静态资源:http://localhost:8080/index.html动态资源:http://localhost:8080/hello?name=YourName不存在的资源:http://localhost:8080/nonexistent.html

总结

通过以上详细步骤,我们成功实现了一个功能完整的自定义Tomcat服务器 - CodingTomcat。它具有以下特性:

基于Socket通信:使用Java Socket API实现底层通信请求和响应封装:提供了Request和Response类来解析请求和生成响应静态资源处理:能够服务HTML、CSS、JavaScript和图像文件动态资源处理:通过Servlet接口支持动态内容生成并发处理:使用线程池处理多个并发请求错误处理:提供了404和500错误页面

这个实现虽然简单,但涵盖了Web服务器的核心功能,可以作为学习Web服务器工作原理的良好起点。你可以根据需要进一步扩展功能,如支持更多的HTTP方法、会话管理、过滤器等。

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧