上一篇文章我们了解了如何使用Netty编写一个极简的Http服务器 ,这一篇文章在上一篇文章的基础上,进一步编写一个静态资源服务器。
首先,HttpServer
类与之前相同,不需要作修改,具体代码请见使用Netty编写一个极简的Http服务器 。我们修改HttpRequestHandler
,来实现对静态资源请求的响应。
为了方便对Http请求的处理,我们先作如下规定:
- 如果请求URI为“/”或“/index.html”,则直接返回index.html文件;
- 如果请求URI以“/static”开头,则从
/src/main/resources/static
目录下根据URI中的文件名查找对应文件并返回给浏览器; - 如果请求URI不符合以上规则,则直接返回404未找到的Http响应。
首先我们在/src/main/resources
目录下创建static
文件夹,并添加几个测试文件,目录结构大概如下:
src
└── main
├── java
│ └── ...
└── resources
├── index.html
└── static
├── test-image.jpg
├── test.txt
└── 测试.txt
对HttpRequestHandler
的channelRead0
方法修改如下:
public class HttpRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
System.out.println("request uri: " + msg.uri());
if ("/".equals(msg.uri()) || "/index.html".equals(msg.uri())) {
handleResource(ctx, msg, "index.html");
} else if (msg.uri().startsWith("/static")) {
handleResource(ctx, msg, msg.uri()