⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 defaultservlet.java

📁 基于java nio实现的http服务器
💻 JAVA
字号:
package org.sse.http;

import java.io.*;
import java.nio.channels.FileChannel;
import java.util.HashMap;

/**
 * @author Taylor Cowan
 */
public class DefaultServlet {
	private static HashMap cache = new HashMap();

	public void service(HttpRequest req, HttpResponse res) throws IOException {
		FileDescriptor fd = getDescriptor(req, req.getRequestedResource());
		if (fd.lastModified <= req.getModifiedSince())
			res.sendError(304, "NOT MODIFIED");
		else
			sendFileContent(res, fd);
			
		if (req.closeAfterResponse())
			res.close();
	}

	private FileDescriptor getDescriptor(HttpRequest req, String url)
		throws IOException {
		return cache.containsKey(url)
			? (FileDescriptor) cache.get(url)
			: cacheResource(req, url);
	}
	
	private void sendFileContent(HttpResponse res, FileDescriptor fd)
		throws IOException {
		res.setContentLength(fd.size);
		res.setContentType(fd.contentType);
		res.setLastModified(fd.lastModified);
		res.sendFile(fd.data);
	}

	private FileDescriptor cacheResource(HttpRequest req, String url)
		throws IOException {
		String realPath = req.getServletContext().getRealPath(url);
		File f = new File(realPath);
		if (! f.exists()) return null;
		FileDescriptor fd = new FileDescriptor();	
		fd.lastModified = f.lastModified();
		fd.size = f.length();
		fd.contentType = req.getServletContext().getMimeType(url);
		FileChannel from = new FileInputStream(f).getChannel();
		fd.data = from.map(FileChannel.MapMode.READ_ONLY, 0, from.size());
		from.close();
		cache.put(url, fd);
		return fd;
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -