javaweb学习(day07-手动实现tomcat)
在这个例子中,我们将手动实现一个简单的HTTP服务器,用于处理静态文件和简单的servlet处理。
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
public class SimpleWebServer {
private int port;
private String webAppRoot;
private Map<String, HttpServlet> servlets = new HashMap<>();
public SimpleWebServer(int port, String webAppRoot) {
this.port = port;
this.webAppRoot = webAppRoot;
}
public void addServlet(String path, HttpServlet servlet) {
servlets.put(path, servlet);
}
public void start() throws IOException {
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server started on port " + port);
while (true) {
Socket clientSocket = serverSocket.accept();
handleRequest(clientSocket);
}
}
private void handleRequest(Socket clientSocket) throws IOException {
InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream();
// 读取请求信息
Request request = new Request(inputStream);
System.out.println("Request URI: " + request.getUri());
// 根据URI路径处理请求
if (servlets.containsKey(request.getUri())) {
HttpServlet servlet = servlets.get(request.getUri());
servlet.service(request, new Response(outputStream));
} else {
String filePath = webAppRoot + request.getUri();
File file = new File(filePath);
if (file.exists()) {
FilesUtil.copy(file, outputStream);
} else {
String errorMessage = "HTTP/1.1 404 File Not Found\r\nContent-Type: text/html\r\n\r\n";
outputStream.write(errorMessage.getBytes());
}
}
outputStream.close();
inputStream.close();
clientSocket.close();
}
public static void main(String[] args) throws IOException {
SimpleWebServer server = new SimpleWebServer(8080, "webapp");
server.addServlet("/hello", new HelloServlet());
server.start();
}
}
class Request {
private String uri;
pub
评论已关闭