java项目实践-webapp-mytomcat-day16

发布时间 2023-10-15 11:22:24作者: chenwen0511

1. http协议

CS架构

建立连接“三次握手” 断开连接 “四次挥手”
三次握手:
client:可以与你建立连接吗?
server:可以的
client: 我也可以了
四次挥手:
client:我要断开
server:可以断开
server:我要断开
client:可以断开
双方都有一个确认 断开的过程 因为连接的建立 双方都有资源打开 都有port号被占用 双方需要将打开的资源关闭掉

请求的格式:

响应的格式:

2. 自定义的web框架


核心:Request Response类
applet
servlet

3. 具体实现

Request Response

package com.msb.mytomcat;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Auther: jack.chen
 * @Date: 2023/10/15 - 10 - 15 - 9:24
 * @Description: com.msb.mytomcat
 * @version: 1.0
 */
public class Request {
    //请求方法 GET POST PUT DELETE ...
    private String requestMethod;

    // 请求的url
    private String requestUrl;

    // 构造方法 将请求的inputStream 转化成Request对象
    public Request(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("\r\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;
    }

    @Override
    public String toString() {
        return "Request{" +
                "requestMethod='" + requestMethod + '\'' +
                ", requestUrl='" + requestUrl + '\'' +
                '}';
    }
}

package com.msb.mytomcat;

import java.io.IOException;
import java.io.OutputStream;

/**
 * @Auther: jack.chen
 * @Date: 2023/10/15 - 10 - 15 - 9:24
 * @Description: com.msb.mytomcat
 * @version: 1.0
 */
public class Response {
    private OutputStream outputStream;

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    // 将返回的str 包装成前端能识别的 响应
    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("\r\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();


    }
}

maping

package com.msb.mytomcat;

import java.util.HashMap;

/**
 * @Auther: jack.chen
 * @Date: 2023/10/15 - 10 - 15 - 10:06
 * @Description: com.msb.mytomcat
 * @version: 1.0
 */
// 请求utl 与 处理类servlet 映射关系
public class Mapping {
    public static HashMap<String, String> map = new HashMap<>();

    static {
        map.put("/mytomcat", "com.msb.mytomcat.Servlet");
    }

    public HashMap<String, String> getMap(){
        return map;
    }
}

抽象类HttpServlet

package com.msb.mytomcat;

import java.io.IOException;

/**
 * @Auther: jack.chen
 * @Date: 2023/10/15 - 10 - 15 - 10:10
 * @Description: com.msb.mytomcat
 * @version: 1.0
 * 抽象类
 */
public abstract class HttpServlet {
    public static final String METHOD_GET = "GET";
    public static final String METHOD_POST = "POST";

    public abstract void doGet(Request request, Response response) throws IOException;
    public abstract void doPost(Request request, Response response) throws IOException;

    // 根据请求的方式 调用对应的方法
    public void service(Request request, Response response) throws IOException {
        if (METHOD_GET.equals(request.getRequestMethod())){
            doGet(request, response);
        } else if (METHOD_POST.equals(request.getRequestMethod())){
            doPost(request, response);
        }


    }

}

实现类Servlet

package com.msb.mytomcat;

import java.io.IOException;

/**
 * @Auther: jack.chen
 * @Date: 2023/10/15 - 10 - 15 - 10:23
 * @Description: com.msb.mytomcat
 * @version: 1.0
 */
public class Servlet extends HttpServlet{
    @Override
    public void doGet(Request request, Response response) throws IOException {
        response.write("get method !");
    }

    @Override
    public void doPost(Request request, Response response) throws IOException {
        response.write("post method !");

    }
}

服务端:

package com.msb.mytomcat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Auther: jack.chen
 * @Date: 2023/10/15 - 10 - 15 - 10:26
 * @Description: com.msb.mytomcat
 * @version: 1.0
 * 服务端
 */
public class Server {

    public static void startServer(int port) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
        ServerSocket serverSocket = new ServerSocket(port);

        Socket socket = null;

        while (true){
            socket = serverSocket.accept();

            // input output

            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();

            Request request = new Request(inputStream);
            Response response = new Response(outputStream);

            String url = request.getRequestUrl();
            String clazz = new Mapping().getMap().get(url);// 处理类的包
            if(clazz!=null){
                Class<Servlet> servletClass = (Class<Servlet>) Class.forName(clazz);
                Servlet servlet = servletClass.newInstance();
                servlet.service(request, response);
                System.out.println("200 ok  "+ request.toString());
            }

        }

    }

    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException {
        startServer(8080);
    }
}

4. 启动