首页 > 编程语言 >java项目实践-webapp-mytomcat-day16

java项目实践-webapp-mytomcat-day16

时间:2023-10-15 11:22:57浏览次数:44  
标签:10 java String day16 IOException mytomcat public

目录

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. 启动

标签:10,java,String,day16,IOException,mytomcat,public
From: https://www.cnblogs.com/cavalier-chen/p/17765421.html

相关文章

  • java学习笔记day03
    java学习笔记day03数据类型public class 数据类型 {  public static void main(String[] args){    //整数类型    byte num1 = 10;    short num2 = 200;    int num3 = 3000;    long num4 = 400000L;    ......
  • JavaWeb-Maven的应用
    目录1.MavenPOM2.pom.xml内容MavenPOMPOM(ProjectObjectModel,项目对象模型)是Maven工程的基本工作单元,是一个XML文件,包含了项目的基本信息,用于描述项目如何构建,声明项目依赖,等等。执行任务或目标时,Maven会在当前目录中查找POM。它读取POM,获取所需的配置信息,然......
  • 从零开发一款图片编辑器(使用html5+javascript)
    最近开发了一个图片编辑器,类似于photoshop的网页版,源码参考自GitHub上,顺便也总结下使用html+js开发一个编辑器需要用到哪些知识点。预览地址:https://ps.gitapp.cngithub地址:https://github.com/photopea/photopea架构设计选型:jquery.js和blueimp-canvas.js都是强大的......
  • JAVA大文件(10G以上)的上传下载实现技术
    在现代互联网应用中,经常需要上传和下载大文件,如视频、音频、数据库备份等等。对于Java开发者来说,处理大文件上传下载是一个非常常见的需求。然而,由于Java内存限制和网络传输速度的限制,处理大文件上传下载需要一些特殊的技术。本文将介绍一种基于流的方式来实现Java大文件的上传和......
  • 深入理解 JavaScript 时间分片:原理、应用与代码示例解析
    JavaScript时间分片(TimeSlicing)是一种优化技术,用于将长时间运行的任务拆分为多个小任务,以避免阻塞主线程,提高页面的响应性和性能。本文将详细解释JavaScript时间分片的原理、应用场景,并通过代码示例帮助读者更好地理解和应用该技术。本文首发于:kelen.cc概念时间分片(TimeSl......
  • Javascript、axios、vue基础命令快速学习
    1.js:JavaScript基础学习JavaScript基础学习简单案例1.点击img1,则展示img1图片默认,点击img2则展示img2图片2.输入框鼠标聚焦onfocus后,显示小写toLowerCase(),失去焦点onblur后显示大写toUpperCase()3.点击全选按钮,所有复选框为被选中状态,点击反选则取消勾选状态JavaScrip......
  • JavaWeb-JDBC增删改查
    目录1.MySQL准备2.JDBC项目3.JDBC新增4.JDBC查询5.JDBC修改6.JDBC删除内容MySQL准备新建表t_personCREATETABLE`t_person`(`id`int(11)NOTNULLAUTO_INCREMENTCOMMENT'主键',`name`varchar(30)NOTNULLCOMMENT'姓名',`birthdate`datetim......
  • Java内存区域
    图示Java1.8以前JDK1.8:说明线程私有的:程序计数器机栈本地方法栈线程共享的:堆方法区直接内存(非运行时数据区的一部分)程序计数器程序计数器程序计数器是一块较小的内存空间,可以看作是当前线程所执行的字节码的行号指示器。字节码解释器工作时通过改变这个计数器的值来选取下一条......
  • Java基础-初识JDBC
    目录1.JDBC简介2.JDBC项目3.JDBC的导入4.JDBC的使用内容JDBC简介什么是JDBCJDBC的全称是Java数据库连接(JavaDatabaseconnect),它是一套用于执行SQL语句的JavaAPI。应用程序可通过这套API连接到关系数据库,并使用SQL语句来完成对数据库中数据的查询、更新和删除等......
  • java基础——枚举类
     枚举枚举对应英文(enumeration,简写enum)。枚举是一组常量的集合。可以这样理解:枚举是一种特殊的类,里面只包含一组有限的特定的对象。枚举的两种实现方式自定义类实现枚举使用enum关键字实现枚举自定义实现枚举不需要提供setXxx方法,因为枚举对象值通常为制度。对枚举对象/属性使用f......