当前位置: 代码迷 >> 综合 >> 《How Tomcat Works》学习(二)——简易的servlet容器
  详细解决方案

《How Tomcat Works》学习(二)——简易的servlet容器

热度:63   发布时间:2024-01-09 01:54:49.0

前言

在《How Tomcat Works》学习(一)中,我们实现了简易的web服务器,但这个服务器并没有servlet的功能。本文目标是实现一个简易的servlet容易,让web服务器可以调用servlet。

 

构建程序

主程序

public class HttpServer {private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";private boolean shutdown = false;public static void main(String[] args) {HttpServer server = new HttpServer();server.await();}public void await() {ServerSocket serverSocket = null;int port = 8080;try {serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));} catch (IOException e) {e.printStackTrace();System.exit(1);}while (!shutdown) {Socket socket = null;InputStream input = null;OutputStream output = null;try {socket = serverSocket.accept();input = socket.getInputStream();output = socket.getOutputStream();Request request = new Request(input);request.parse();Response response = new Response(output);response.setRequest(request);if(request.getUri().startsWith("/servlet/")) {ServletProcessor1 processor = new ServletProcessor1();processor.process(request, response);}else {StaticResourceProcessor processor = new StaticResourceProcessor();processor.process(request, response);}socket.close();shutdown = request.getUri().equals(SHUTDOWN_COMMAND);} catch (Exception e) {e.printStackTrace();continue;}}}
}

主程序和前文的没太大变化,主要是37-43行,增加了判断,当请求的路径以"/servlet/"为起始的话,则调用servlet处理程序,否则还是按照以前的处理方式,读取静态资源并返回给浏览器。

 

Request类

public class Request implements ServletRequest {private InputStream input;private String uri;public Request(InputStream input) {this.input = input;}void parse() {StringBuffer request = new StringBuffer(2048);int i;byte[] buffer = new byte[2048];try {i = input.read(buffer);} catch (IOException e) {e.printStackTrace();i = -1;}for (int j = 0; j < i; j++) {request.append((char) buffer[j]);}System.out.print(request.toString());uri = parseUri(request.toString());}private String parseUri(String requestString) {int index1, index2;index1 = requestString.indexOf(' ');if (index1 != -1) {index2 = requestString.indexOf(' ', index1 + 1);if (index2 > index1)return requestString.substring(index1 + 1, index2);}return null;}public String getUri() {return uri;}//省略重写ServletRequest的方法//......
}

Request类需要实现ServletRequest接口,并且实现其定义的方法。暂时对这些方法都返回null或0或者留空即可,由于比较多,就不列举了。parse和getUri和之前的保持一致

 

Response类

public class Response implements ServletResponse{private static final int BUFFER_SIZE = 1024;private Request request;private OutputStream output;private PrintWriter writer;public Response(OutputStream output) {this.output = output;}void setRequest(Request request) {this.request = request;}void sendStaticResource() throws IOException {byte[] bytes = new byte[BUFFER_SIZE];FileInputStream fis = null;try {File file = new File(Constants.WEB_ROOT, request.getUri());if (file.exists()) {fis = new FileInputStream(file);int ch = fis.read(bytes, 0, BUFFER_SIZE);output.write(new String("HTTP/1.1 200 OK\r\n\r\n").getBytes());while (ch != -1) {output.write(bytes, 0, ch);ch = fis.read(bytes, 0, BUFFER_SIZE);}} 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" + "<h1>File Not Found</h1>";output.write(errorMessage.getBytes());}} catch (Exception e) {System.out.println(e.toString());} finally {if (fis != null)fis.close();}}//省略ServletResponse重写的方法//......
}

类似Request类,Response类需要实现ServletResponse。除了需要重写ServletResponse的方法外,其余实现与之前的基本一致

 

静态资源处理类

这里的静态资源处理类是在主程序中,当浏览器访问非servlet路径时调用,主要就是调用Response的sendStaticResource,就像第一篇文章读取一个html页面一样。

public class StaticResourceProcessor {public void process(Request request, Response response) {try {response.sendStaticResource();} catch (Exception e) {e.printStackTrace();}}
}

 

servlet类的处理

serlvet的处理首先是获取调用的路径,根据名称通过URLClassLoader反射来创建,因此输入servlet名称对应其类名。

public class ServletProcessor1 {public void process(Request request, Response response) {String uri = request.getUri();String servletName = uri.substring(uri.lastIndexOf("/") + 1);URLClassLoader loader = null;try {URL[] urls = new URL[1];URLStreamHandler urlStreamHandler = null;File classPath = new File(Constants.WEB_ROOT);String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString();urls[0] = new URL(null, repository, urlStreamHandler);loader = new URLClassLoader(urls);} catch (Exception e) {e.printStackTrace();}Class myClass = null;try {myClass = loader.loadClass(servletName);} catch (ClassNotFoundException e) {e.printStackTrace();}Servlet servlet = null;try {servlet = (Servlet) myClass.newInstance();servlet.service((ServletRequest)request, (ServletResponse)response);} catch (Exception e) {e.printStackTrace();}}
}

在这段代码中,因为用户输入的路径直接对应servlet类名,所以编写的servlet要放在一个默认package下面,否则就找不到对应的servlet类了。

 

serlvet类

我们再写一个简单的servlet

public class PrimitiveServlet implements Servlet{@Overridepublic void destroy() {System.out.println("destroy");}@Overridepublic ServletConfig getServletConfig() {// TODO Auto-generated method stubreturn null;}@Overridepublic String getServletInfo() {// TODO Auto-generated method stubreturn null;}@Overridepublic void init(ServletConfig arg0) throws ServletException {System.out.println("init");}@Overridepublic void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {System.out.println("from service");PrintWriter out = response.getWriter();out.print("HTTP/1.1 200 OK\r\n\r\n");out.println("Hello. Roses are red.");out.println("Violet are blue.");}
}

启动主程序,输入路径http://localhost:8080/servlet/PrimitiveServlet,成功调用了PrimitiveServlet

我们也可以输入http://localhost:8080/hello.html,可以像前文那样获取对应的静态资源。

 

小结

本文实现了一个简单的servlet,就是通过路径名进行反射创建一个servlet类,然后调用其service方法。实际的javaweb开发中,常常会通过web.xml配置文件mapping映射,不会直接在地址栏输入servlet的类名。另外cookies、session之类的信息我们并没有解析,这些后面也需要实现。

  相关解决方案