访问: http://localhost:10086/mytomcat
代码结构
MyTomcat/
└── src/
└── com/
└── zhang/
├── MyServer.java
├── MyRequest.java
├── MyResponse.java
├── MyMapping.java
├── MyServlet.java
└── MyHttpServlet.java
核心类功能说明
- MyServer.java
- 服务器主类,负责启动并监听端口(默认10086)
- 接受客户端请求,创建 MyRequest 和 MyResponse 对象
- 根据URL映射找到对应的Servlet进行处理
-
MyRequest.java
- 请求处理类,解析HTTP请求中的方法(GET/POST)和URL
- 提供getter/setter方法访问请求信息
-
MyResponse.java
- 响应处理类,构建HTTP响应
- 提供 write 方法发送HTML响应内容到客户端
-
MyMapping.java
- URL映射配置类,维护URL到Servlet类的映射关系
- 目前配置了: /mytomcat -> com.zhang.MyServlet
- MyHttpServlet.java
- Servlet抽象基类,定义了处理GET和POST请求的抽象方法
- 提供 service 方法根据请求类型调用对应的处理方法
- MyServlet.java
- 具体的Servlet实现类,继承自 MyHttpServlet
- 实现了 doGet 和 doPost 方法,返回不同的响应内容
工作流程
- 启动服务器:运行 MyServer.main 方法,服务器在端口10086启动
- 客户端请求:当访问 http://localhost:10086/mytomcat 时
- 请求解析: MyServer 创建 MyRequest 和 MyResponse 对象
- 映射查找:通过 MyMapping 找到对应的 MyServlet 类
- 请求处理:调用 MyServlet 的 service 方法,根据请求类型调用 doGet 或 doPost
- 响应发送: MyResponse 构建并发送HTTP响应到客户端
访问测试
- 可以通过浏览器访问 http://localhost:10086/mytomcat 来测试GET请求
- 对于POST请求,可以使用curl或其他工具发送请求
这个简单的Tomcat模拟实现了基本的HTTP请求处理和Servlet机制,展示了Web服务器的核心工作原理。
代码
MyHttpServlet.java
java
package com.zhang;
public abstract class MyHttpServlet {
//定义常量
public static final String METHOD_GET = "GET";
public static final String METHOD_POST = "POST";
public abstract void doGet(MyRequest request, MyResponse response) throws Exception;
public abstract void doPost(MyRequest request, MyResponse response)throws Exception;
/**
* 根据请求方式来判断使用那种处理方法
*
* @param request
* @param response
*/
public void service(MyRequest request, MyResponse response) throws Exception{
if (METHOD_GET.equals(request.getRequestMethod())) {
System.out.println(METHOD_GET + "请求");
doGet(request, response);
} else if (METHOD_POST.equals(request.getRequestMethod())) {
System.out.println(METHOD_POST + "请求");
doPost(request, response);
}
}
}
MyMapping
java
package com.zhang;
import java.util.HashMap;
public class MyMapping {
public static HashMap<String, String> mapping = new HashMap<String, String>();
static {
// http://localhost:10086/mytomcat 可以运行
mapping.put("/mytomcat", "com.zhang.MyServlet");
}
public HashMap<String, String> getMapping() {
return mapping;
}
}
MyRequest
java
package com.zhang;
import java.io.IOException;
import java.io.InputStream;
/**
* 请求对象
*/
public class MyRequest {
//请求方法 GET、POST
private String requestMethod;
//请求地址
private String requestUrl;
//构造方法
public MyRequest(InputStream inputStream) throws IOException {
//缓冲空间
byte[] buffer = new byte[1024];
//读取数据的长度
int len = 0;
//定义请求的变量
String str = null;
if ((len = inputStream.read(buffer)) > 0) {
str = new String(buffer, 0, len);
}
//GET /HTTP /1.1
String data=str.split("\n")[0];
String [] params=data.split(" ");
this.requestMethod=params[0];
this.requestUrl=params[1];
}
public String getRequestMethod() {
return requestMethod;
}
public void setRequestMethod(String requestMethod) {
this.requestMethod = requestMethod;
}
public String getRequestUrl() {
return requestUrl;
}
public void setRequestUrl(String requestUrl) {
this.requestUrl = requestUrl;
}
}
MyResponse
java
package com.zhang;
import java.io.IOException;
import java.io.OutputStream;
public class MyResponse {
private OutputStream outputStream;//输出
public MyResponse(OutputStream outputStream) {
this.outputStream = outputStream;
}
public void write(String str) throws IOException {
StringBuilder builder = new StringBuilder();
builder.append("Http/1.1 200 ok\n")
.append("Content-Type:text/html\n")
.append("<html>")
.append("<body>")
.append("<h1>" + str + "</h1>")
.append("</body>")
.append("</html>");
this.outputStream.write(builder.toString().getBytes());
this.outputStream.flush();
this.outputStream.close();
}
}
MyServer
java
package com.zhang;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MyServer {
/**
* 定义服务器的接受程序,接受socket请求
*
* @param port
*/
public static void StartServer(int port) throws Exception {
//定义服务端套接字
ServerSocket serverSocket = new ServerSocket(port);
//定义客户端套接字
Socket socket = null;
while (true) {
socket = serverSocket.accept();
//获取输入流和输出流
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = socket.getOutputStream();
//定义请求对象
MyRequest request = new MyRequest(inputStream);
MyResponse response = new MyResponse(outputStream);
String clazz = new MyMapping().getMapping().get(request.getRequestUrl());
if (clazz != null) {
Class<MyServlet> myServletClass = (Class<MyServlet>) Class.forName(clazz);
//根据myServletClass创建对象
MyServlet myServlet = myServletClass.newInstance();
myServlet.service(request, response);
}
}
}
public static void main(String[] args) {
try {
StartServer(10086);
} catch (Exception e) {
e.printStackTrace();
}
}
}
MyServlet
java
package com.zhang;
public class MyServlet extends MyHttpServlet{
@Override
public void doGet(MyRequest request, MyResponse response) throws Exception{
response.write("get myTomcat 哈哈哈");
}
@Override
public void doPost(MyRequest request, MyResponse response)throws Exception {
response.write("post myTomcat");
}
}