关于最火爆的服务器Tomcat你真的了解吗?

发布时间:2020-03-11 23:00:46 作者:qq593e097eaab3c
来源:网络 阅读:215

作为Apache 软件基金会的Jakarta 项目中的一个核心项目,Tomcat因技术先进、性能稳定,而且免费,因而深受Java 爱好者的喜爱并得到了部分软件开发商的认可,成为目前比较流行的Web 应用服务器。接下来我就会为大家分享一下我对Tomcat的理解,希望可以帮到大家。
关于最火爆的服务器Tomcat你真的了解吗?
声明:
1:本系列仅记录本人读<<深入剖析Tomcat>>此书的一些感悟,不足之处,留言指正,不胜感激。2:本系列所有代码参照<<深入剖析Tomcat>>,不对之处,留言指正,不胜感激。
概念:传送门:tomcat百度百科,这里说一个点,tomcat是轻量级的javaweb服务器,用于处理servlet/jsp等动态网页,虽说也可以处理静态网页,但相比apache而言还是逊色不少。有兴趣的朋友可以另行了解一下 nginx, iis,apache等其他较为流行的web服务器。
使用过tomcat的朋友应该知道,当java web项目部署到tomcat后,在浏览器地址栏里输入:http://localhost:8080/资源路径,便可以访问项目资源。在这一过程中,tomcat扮演调度中心的角色,接收浏览器发起资源请求并解析,根据解析结果分发给指定web项目处理,然后根据处理结果,对浏览器响应。对此,我们来研究一下,tomcat是怎么做到的。
项目结构:

MyTomcat
接收请求(Request)
想接收浏览发起的请求,需要做几手准备, 1:监听端口(8080), 2:接收浏览器连接(socket连接) 3:解析HTTP请求数据。下面是代码模拟:

第一第二步: 使用httpServer模拟tomcat调度中心
/**
 * 模拟tomcat的核心类
 */public class HttpServer {
    //tomcat项目绝对路径, 所有web项目都丢在webapps目录下
    public static final String WEB_ROOT =
            System.getProperty("user.dir") + File.separator  + "webapps";
    // 模拟tomcat关闭命令
    private static final String SHUTDOWN_CMD = "/SHUTDOWN";
    private boolean shutdown = false;
    //持续监听端口
    @SuppressWarnings("resource")
    public void accept() {
        ServerSocket serverSocket = null;
        try {
            // 启动socket服务, 监听8080端口,
            serverSocket =  new ServerSocket(8080, 1, InetAddress.getByName("127.0.0.1"));
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("启动myTomcat服务器失败:" + e.getMessage(), e);
        }
        // 没接收到关闭命令前一直监听
        while (!shutdown) {
            Socket socket = null;
            InputStream in = null;
            OutputStream out = null;
            try {
                // 接收请求
                socket = serverSocket.accept();
                in = socket.getInputStream();
                out = socket.getOutputStream();
                // 将浏览器发送的请求信息封装成请求对象
                Request request = new Request(in);
                request.parseRequest();
                // 将相应信息封装相应对象
                //此处简单响应一个静态资源文件
                Response response = new Response(out);
                //模拟页面跳转
                response.sendRedircet(request.getUri());
                socket.close();
                //如果是使用关闭命令,停止监听退出
                shutdown = request.getUri().equals(SHUTDOWN_CMD);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
        }
    }
    public static void main(String[] args) {
        new HttpServer().accept();
    }
}
第三步,使用HttpReqeust封装请求相关信息
/**
 * 请求信息封装对象
 */public class Request {
    // 浏览器socket连接的读流
    private InputStream in;
    //请求行信息信息中的uri
    private String uri;
    public Request(InputStream in) {
        this.in = in;
    }
    // 解析浏览器发起的请求
    public void parseRequest() {
        // 暂时忽略文件上传的请求,假设都字符型请求
        byte[] buff = new byte[2048];
        StringBuffer sb = new StringBuffer(2048);
        int len = 0;
        //请求内容
        try {
            len = in.read(buff);
            sb.append(new String(buff, 0, len));
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.print(sb.toString());
        //解析请求行中uri信息
        uri = this.parseUri(sb.toString());
    }

    /**tomcat接收浏览器发起的请求是居于http协议的,请求内容格式:*/
    /**请求行:请求方式   请求uri 协议版本*/
    //GET /index HTTP/1.1    
    /**请求头:以key-value形式存在*/
    //Host: localhost:8080
    //Connection: keep-alive
    //Upgrade-Insecure-Requests: 1
    //User-Agent: Mozilla/5.0 .........
    //Accept: text/html,application/xhtml+xml......
    //Accept-Encoding: gzip, deflate, br
    //Accept-Language: zh-CN,zh;q=0.9
    //Cookie: .....
    /**请求体: 请求头回车格一行就是请求体,get方式请求体为空*/
    public String parseUri(String httpContent) {
        //传入的内容解析第一行的请求行即可:
        //请求行格式:  请求方式   请求uri 协议版本     3个内容以空格隔开
        int beginIndex = httpContent.indexOf(" ");
        int endIndex;
        if(beginIndex > -1) {
            endIndex = httpContent.indexOf(" ", beginIndex + 1);
            if(endIndex > beginIndex) {
                return httpContent.substring(beginIndex, endIndex).trim();
            }
        }
        return null;
    }

    public String getUri() {
        return uri;
    }
}
假设,浏览器发起请求:http://localhost:8080/hello/index.html HttpServer中socket通过输入流获取到的数据是:
GET /hello/index.html HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
Cookie: Hm_lvt_aa5c701f4f646931bf78b6f40b234ef5=1516445118,1516604544,1518416964,1518497222; JSESSIONID=79367FD9A55B9B442C4ED112D10FDAC5
HttpServer 将上述的数据交于HttpRequest对象处理,该对象调用parseRequest解析,获取请求行中的uri 数据, 分析该数据, 得到上下文路径,项目名,资源名。统称资源路径。
上面数据得到: hello 项目下, index.html 资源(没有上下文路径)
响应请求
当从请求信息中获取uri后,进而获取到hello 项目, index.html资源, 响应请求就可以简单认为根据资源路径查找资源,如果找到,使用socket output流直接输出资源数据即可,如果找不到,输出404信息。

 * 处理响应请求对象
public class Response {
    // 浏览器socket连接的写流
    private OutputStream out;

    public Response(OutputStream out) {
        this.out = out;
    }
    public OutputStream getOutputStream() {
        return out;
    }
    //跳转
    public void sendRedircet(String uri) {

        File webPage = new File(HttpServer.WEB_ROOT, uri);
        FileInputStream fis = null;
        StringBuffer sb = new StringBuffer();
        try {
            //找得到页面是
            if(webPage.exists()&& webPage.isFile()) {
                String respHeader = "HTTP/1.1 200 OK\r\n" +
                  "Content-Type: text/html\r\n" +
                  "Content-Length: #{count}\r\n" +
                  "\r\n";
                fis = new FileInputStream(webPage);
                byte[] buff = new byte[2048];
                int len = 0;
                while( (len = fis.read(buff))!= -1) {
                    sb.append(new String(buff, 0, len));
                }
                respHeader=respHeader.replace("#{count}", sb.length()+"");
                System.out.println(respHeader + sb);
                out.write((respHeader + sb).getBytes());

            }else {
                 //页面找不到时
                String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
                  "Content-Type: text/html\r\n" +
                  "Content-Length: 23\r\n" +
                  "\r\n" +
                  "<h2>File Not Found</h2>";
                out.write(errorMessage.getBytes());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

此处注意, 响应请求数据也必须遵循http协议。
当然,这些内容只是Tomcat中的一部分,想要继续探索关于Tomcat的内容,大家大可继续自行研究或者关注我们,我们也会持续发布相关教程,共同进步。

推荐阅读:
  1. 你真的懂JAVA吗
  2. 你真的了解WebSocket吗?

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

关于最火爆的服务器tomcat你真的了解 omc tomca

上一篇:【从0开始Python开发实战】Django集成Celery

下一篇:MGR单主启动报错处理ERROR 3092

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》