模拟tomcat接收GET、POST请求

访问: http://localhost:10086/mytomcat

代码结构 复制代码
MyTomcat/
└── src/
    └── com/
        └── zhang/
            ├── MyServer.java
            ├── MyRequest.java
            ├── MyResponse.java
            ├── MyMapping.java
            ├── MyServlet.java
            └── MyHttpServlet.java

核心类功能说明

  1. MyServer.java
  • 服务器主类,负责启动并监听端口(默认10086)
  • 接受客户端请求,创建 MyRequest 和 MyResponse 对象
  • 根据URL映射找到对应的Servlet进行处理
  1. MyRequest.java

    • 请求处理类,解析HTTP请求中的方法(GET/POST)和URL
    • 提供getter/setter方法访问请求信息
  2. MyResponse.java

    • 响应处理类,构建HTTP响应
    • 提供 write 方法发送HTML响应内容到客户端
  3. MyMapping.java

  • URL映射配置类,维护URL到Servlet类的映射关系
  • 目前配置了: /mytomcat -> com.zhang.MyServlet
  1. MyHttpServlet.java
  • Servlet抽象基类,定义了处理GET和POST请求的抽象方法
  • 提供 service 方法根据请求类型调用对应的处理方法
  1. MyServlet.java
  • 具体的Servlet实现类,继承自 MyHttpServlet
  • 实现了 doGet 和 doPost 方法,返回不同的响应内容

工作流程

  1. 启动服务器:运行 MyServer.main 方法,服务器在端口10086启动
  2. 客户端请求:当访问 http://localhost:10086/mytomcat
  3. 请求解析: MyServer 创建 MyRequest 和 MyResponse 对象
  4. 映射查找:通过 MyMapping 找到对应的 MyServlet 类
  5. 请求处理:调用 MyServlet 的 service 方法,根据请求类型调用 doGet 或 doPost
  6. 响应发送: 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");
    }
}
相关推荐
渣哥7 分钟前
99% 的人没搞懂:Semaphore 到底是干啥的?
java
J2K17 分钟前
JDK都25了,你还没用过ZGC?那真得补补课了
java·jvm·后端
kfyty72519 分钟前
不依赖第三方,不销毁重建,loveqq 框架如何原生实现动态线程池?
java·架构
isysc12 小时前
面了一个校招生,竟然说我是老古董
java·后端·面试
道可到5 小时前
Java 反射现代实践速查表(JDK 11+/17+)
java
道可到5 小时前
Java 反射现代实践指南(JDK 11+ / 17+ 适用)
java
玉衡子5 小时前
九、MySQL配置参数优化总结
java·mysql
叽哥5 小时前
Kotlin学习第 8 课:Kotlin 进阶特性:简化代码与提升效率
android·java·kotlin
麦兜*5 小时前
MongoDB Atlas 云数据库实战:从零搭建全球多节点集群
java·数据库·spring boot·mongodb·spring·spring cloud
带刺的坐椅5 小时前
DamiBus v1.1.0 发布(给单体多模块解耦)
java·事件总线·damibus