IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> 基于传统I/O或Netty简单实现tomcat容器 -> 正文阅读

[Java知识库]基于传统I/O或Netty简单实现tomcat容器

总体思路

以往部署servlet项目都是部署在tomcat上,并且有一个全局的web.xml配置实现的servlet和filter过滤器,在这里我们自定义一个web.properties来代替web.xml;除此之外,我们需要做的呀Request和Response来处理http请求和响应,也要自定义servlet来处理http请求的相应后端业务逻辑,servlet与url的映射关系我们配置在web.properties中。

1、环境准备

自定义Servlet

servlet抽象类

public abstract class AbstractServlet {

    public void service(MyRequest request, MyResponse response) throws Exception {
        if ("GET".equals(request.getMethod())) {
            doGet(request, response);
        } else {
            doPost(request, response);
        }
    }

    public abstract void doGet(MyRequest request, MyResponse response) throws Exception;
    public abstract void doPost(MyRequest request, MyResponse response) throws Exception;
}

servlet实现类MyFirstServlet

public class MyFirstServlet extends AbstractServlet {

    @Override
    public void doGet(MyRequest request, MyResponse response) throws Exception {
        this.doPost(request, response);
    }

    @Override
    public void doPost(MyRequest request, MyResponse response) throws Exception {
        response.write("MyFirstServlet done!");
    }
}

servlet实现类MySecondServlet

public class MySecondServlet extends AbstractServlet {
    @Override
    public void doGet(MyRequest request, MyResponse response) throws Exception {
        this.doPost(request, response);
    }

    @Override
    public void doPost(MyRequest request, MyResponse response) throws Exception {
        response.write("MySecondServlet done!");
    }
}

2、自定义配置文件web.properties

servlet.first.url=/first
servlet.first.className=com.mxd.nettystudy.tomcat.servlet.MyFirstServlet

servlet.second.url=/second
servlet.second.className=com.mxd.nettystudy.tomcat.servlet.MySecondServlet

3、基于传统I/O实现Tomcat

自定义Request=>MyRequest

public class MyRequest {
    private String method;
    private String url;

    public MyRequest(InputStream is) {
        try {
            String content = "";
            byte[] bytes = new byte[1024];
            int len = 0;
            if ((len = is.read(bytes)) > 0) {
                content = new String(bytes, 0 ,len);
            }
            // 这里相当于是 "GET /second HTTP/1.1"
            String line = content.split("\\n")[0];
            String[] split = line.split("\\s");
            this.method = split[0];
            this.url = split[1].split("\\s")[0];
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getUrl() {
        return url;
    }

    public String getMethod() {
        return method;
    }
}

Http请求内容参考

GET /second HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
sec-ch-ua: " Not A;Brand";v="99", "Chromium";v="99", "Google Chrome";v="99"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "macOS"
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.83 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: none
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9

自定义Response=>MyResponse

public class MyResponse {
    private OutputStream os;

    public MyResponse(OutputStream os) {
        this.os = os;
    }

    public void write(String msg) throws IOException {
        StringBuilder sb = new StringBuilder();
        sb.append("HTTP/1.1 200 OK\n")
                .append("Content-Type: text/html;\n")
                .append("\r\n")
                .append(msg);
        os.write(sb.toString().getBytes());
    }
}

自定义Tomcat启动类

public class TomcatApplication {
    private int port = 8080;
    private ServerSocket serverSocket;
    // Map存储url与servlet的映射
    private Map<String, AbstractServlet> servletMapping = new HashMap<>();
    // 存储web.properties配置文件
    private Properties webProperties = new Properties();

    // 容器启动时加载配置文件
    public void init() {
        try {
            String path = this.getClass().getResource("/").getPath();
            FileInputStream fis = new FileInputStream(path + "web.properties");
            webProperties.load(fis);
            for (Object k : webProperties.keySet()) {
                String key = k.toString();
                if (key.endsWith(".url")) {
                    String url = webProperties.getProperty(key);
                    String className = webProperties.getProperty(key.replaceAll("\\.url$", "") + ".className");
                    AbstractServlet servlet = (AbstractServlet) Class.forName(className).newInstance();
                    servletMapping.put(url, servlet);
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start(){
        init();
        try {
            serverSocket = new ServerSocket(this.port);
            System.out.println("自定义tomcat启动-----监听端口:" + this.port);
            while (true) {
                // 监听端口
                Socket accept = serverSocket.accept();
                System.out.println(accept.getRemoteSocketAddress());
                // 处理请求
                process(accept);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void process(Socket accept) throws Exception {
        InputStream is = accept.getInputStream();
        OutputStream os = accept.getOutputStream();

        MyRequest request = new MyRequest(is);
        MyResponse response = new MyResponse(os);

        String url = request.getUrl();
        // 处理url
        if (servletMapping.containsKey(url)) {
            servletMapping.get(url).service(request, response);
        } else {
            response.write("404-Not Found");
        }

        os.flush();
        os.close();

        is.close();
        accept.close();
    }

    public static void main(String[] args) {
        // 启动tomcat服务
        new TomcatApplication().start();
    }
}

4、基于Netty实现Tomcat

重构Request=>MyRequest

public class MyRequest {
    private ChannelHandlerContext ctx;
    private HttpRequest request;

    public MyRequest(ChannelHandlerContext ctx, HttpRequest request) {
        this.ctx = ctx;
        this.request = request;
    }

    public String getUrl() {
        return this.request.uri();
    }

    public String getMethod() {
        return this.request.method().name();
    }

    // 获取指定参数值
    public String getParameter(String paramName) {
        Map<String, List<String>> parameters = getParameters();
        List<String> paramValues = parameters.get(paramName);
        return Objects.nonNull(paramValues)? paramValues.get(0): null;
    }

    // 解析http的URL请求中所有参数键值对
    public Map<String, List<String>> getParameters() {
        QueryStringDecoder queryStringDecoder = new QueryStringDecoder(this.request.uri());
        return queryStringDecoder.parameters();
    }
}

重构Response=>MyResponse

public class MyResponse {
    private ChannelHandlerContext ctx;
    private HttpRequest request;

    public MyResponse(ChannelHandlerContext ctx, HttpRequest request) {
        this.ctx = ctx;
        this.request = request;
    }

    public void write(String msg) throws IOException {
        if (!StringUtils.hasText(msg)) return;

        try {
            FullHttpResponse response = new DefaultFullHttpResponse(
                    // 设置版本为HTTP 1.1
                    HttpVersion.HTTP_1_1,
                    // 设置状态响应码
                    HttpResponseStatus.OK,
                    // 设置输出内容编码格式
                    Unpooled.wrappedBuffer(msg.getBytes(HttpConstants.DEFAULT_CHARSET))
            );

            response.headers().set("Content-Type", "text/html");
            ctx.write(response);
        } finally {
            ctx.flush();
            ctx.close();
        }
    }
}

重构Tomcat启动类[netty实现]

public class TomcatApplication {
    private int port = 8080;
    private ServerSocket serverSocket;
    private Map<String, AbstractServlet> servletMapping = new HashMap<>();
    private Properties webProperties = new Properties();

    // 容器启动时加载配置文件
    public void init() {
        try {
            String path = this.getClass().getResource("/").getPath();
            FileInputStream fis = new FileInputStream(path + "web.properties");
            webProperties.load(fis);
            for (Object k : webProperties.keySet()) {
                String key = k.toString();
                if (key.endsWith(".url")) {
                    String url = webProperties.getProperty(key);
                    String className = webProperties.getProperty(key.replaceAll("\\.url$", "") + ".className");
                    AbstractServlet servlet = (AbstractServlet) Class.forName(className).newInstance();
                    servletMapping.put(url, servlet);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void start(){
        init();
        // netty封装的Reactor模型
        // boss线程
        NioEventLoopGroup boss = new NioEventLoopGroup();
        // work线程
        NioEventLoopGroup work = new NioEventLoopGroup();
        ServerBootstrap server = new ServerBootstrap();

        try {
            server.group(boss, work)
                    // 主线程处理
                    .channel(NioServerSocketChannel.class)
                    // 子线程处理
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            // netty对http的封装,顺序有要求
                            ch.pipeline().addLast(new HttpResponseEncoder());
                            ch.pipeline().addLast(new HttpRequestDecoder());
                            // 业务逻辑处理
                            MyTomcatHandler tomcatHandler = new MyTomcatHandler();
                            tomcatHandler.setServletMapping(servletMapping);
                            ch.pipeline().addLast(tomcatHandler);
                        }
                    })
                    // 主线程配置 最大线程数量128
                    .option(ChannelOption.SO_BACKLOG, 128)
                    // 子线程配置 保持长链接
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture channelFuture = server.bind(port).sync();
            System.out.println("自定义tomcat启动-----端口:" + port);
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            // 关闭线程池
            boss.shutdownGracefully();
            work.shutdownGracefully();
        }

    }

    public static void main(String[] args) {
        // 启动tomcat服务
        new TomcatApplication().start();
    }
}

实现业务处理的handler

public class MyTomcatHandler extends ChannelInboundHandlerAdapter {

    private Map<String, AbstractServlet> servletMapping;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        HttpRequest request = (HttpRequest) msg;
        MyRequest myRequest = new MyRequest(ctx, request);
        MyResponse myResponse = new MyResponse(ctx, request);
        String url = myRequest.getUrl();
        if (servletMapping.containsKey(url)) {
            servletMapping.get(url).service(myRequest, myResponse);
        } else {
            myResponse.write("404-Not Found");
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {

    }

    public Map<String, AbstractServlet> getServletMapping() {
        return servletMapping;
    }

    public void setServletMapping(Map<String, AbstractServlet> servletMapping) {
        this.servletMapping = servletMapping;
    }
}

5、启动Tomcat,运行演示

这里我们启动基于Netty实现的Tomcat,所以直接运行Tomcat的启动类中的main方法new TomcatApplication().start();
控制台效果
在这里插入图片描述
浏览器请求效果
浏览器输入=》http://localhost:8080/first
在这里插入图片描述
浏览器输入=》http://localhost:8080/second
在这里插入图片描述

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-03-31 23:49:43  更:2022-03-31 23:55:17 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 7:02:13-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码