《深入剖析Tomcat》源码学习(边读边更新)

1 篇文章 0 订阅

最近在读《深入剖析Tomcat》这本书,书中附带了很多源码帮助学习.
但是部分源码存在一些小问题需要修复才可以正常运行.
另外有些源码的运行方式也需要特殊注意.

后来发现github上有现成的可运行的代码集合:
vonzhou/HowTomcatWorks
我这里就继续做一些代码的解读吧

第一章

如下图所示,代码清单1-6中直接发送了响应体,缺失了http响应头,需要补充.否则http请求会失败.1-6
修改后的代码:

public void sendStaticResource() throws IOException {
        byte[] bytes = new byte[BUFFER_SIZE];
        FileInputStream fis = null;
        String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
                "Content-type: text/html\r\n" +
                "Content-Length: 23\r\n" +
                "\r\n" +
                "<h1>File Not Found</h1>";
        try {
            File file = new File(HttpServer.WEB_ROOT, request.getUri());
            if (file.exists()) {
                PrintWriter printWriter = new PrintWriter(output);
                printWriter.println("HTTP/1.1 200 OK");
                printWriter.println("Content-Type:text/html;charset=utf-8");
                printWriter.println("Content-length: " + file.length());
                printWriter.println();
                printWriter.flush();
                fis = new FileInputStream(file);
                int ch = fis.read(bytes, 0, BUFFER_SIZE);
                while (ch != -1) {
                    output.write(bytes, 0, ch);
                    ch = fis.read(bytes, 0, BUFFER_SIZE);
                }
                printWriter.close();
            } else {
                output.write(errorMessage.getBytes());
            }
        } catch (Exception e) {
            System.out.println(e.toString());
            output.write(errorMessage.getBytes());
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
    }

第二章

  • PrimitiveServlet.class需要放在webroot目录下,并且最好不要携带package信息,否则需要在webroot目录下建立package的目录.不然会ClassNotFoundException.
  • PrimitiveServlet.service()同样需要补充http响应头.
  • 在webroot下手动编译PrimitiveServlet(需要有servlet-api.jar):
javac -classpath servlet-api.jar PrimitiveServlet.java

第三章

SocketInputStream的read方法是这样的:

public int read()
            throws IOException {
        if (pos >= count) {
            fill();
            if (pos >= count)
                return -1;
        }
        // 将有符号的byte转换为无符号类型
        return buf[pos++] & 0xff;
    }

数组buf里面存储的就是http的请求信息,令人比较好奇的是 buf[pos++] & 0xff 的作用是什么。后来查阅了一些资料,知道了作用是将有符号的byte转换为无符号类型,可以将值域从[-128,127]转为[0,255]。
Java中byte做&0xff运算的原因及解析
java中byte与int的转换原理

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值