模拟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");
    }
}
相关推荐
JH30735 小时前
SpringBoot 优雅处理金额格式化:拦截器+自定义注解方案
java·spring boot·spring
Coder_Boy_6 小时前
技术让开发更轻松的底层矛盾
java·大数据·数据库·人工智能·深度学习
invicinble6 小时前
对tomcat的提供的功能与底层拓扑结构与实现机制的理解
java·tomcat
较真的菜鸟6 小时前
使用ASM和agent监控属性变化
java
黎雁·泠崖7 小时前
【魔法森林冒险】5/14 Allen类(三):任务进度与状态管理
java·开发语言
qq_12498707538 小时前
基于SSM的动物保护系统的设计与实现(源码+论文+部署+安装)
java·数据库·spring boot·毕业设计·ssm·计算机毕业设计
Coder_Boy_8 小时前
基于SpringAI的在线考试系统-考试系统开发流程案例
java·数据库·人工智能·spring boot·后端
Mr_sun.8 小时前
Day06——权限认证-项目集成
java
瑶山8 小时前
Spring Cloud微服务搭建四、集成RocketMQ消息队列
java·spring cloud·微服务·rocketmq·dashboard
abluckyboy8 小时前
Java 实现求 n 的 n^n 次方的最后一位数字
java·python·算法