一个简单的servlet容器

本文涉及的产品
容器镜像服务 ACR,镜像仓库100个 不限时长
简介:

 HttpServer

Java代码   收藏代码
  1. package com.whatsmars.tomcat.servlet;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.io.OutputStream;  
  6. import java.net.InetAddress;  
  7. import java.net.ServerSocket;  
  8. import java.net.Socket;  
  9.   
  10. /** 
  11.  * Created by shenhongxi on 16/3/21. 
  12.  */  
  13. public class HttpServer {  
  14.   
  15.     private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";  
  16.   
  17.     private boolean shutdown = false;  
  18.   
  19.     public static void main(String[] args) {  
  20.         HttpServer server = new HttpServer();  
  21.         server.await();  
  22.     }  
  23.   
  24.     private void await() {  
  25.         ServerSocket serverSocket = null;  
  26.         int port = 8080;  
  27.         try {  
  28.             serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));  
  29.             System.out.println("Server started!");  
  30.         } catch (IOException e) {  
  31.             e.printStackTrace();  
  32.             System.exit(1);  
  33.         }  
  34.   
  35.         while (!shutdown) {  
  36.             Socket socket = null;  
  37.             InputStream input = null;  
  38.             OutputStream output = null;  
  39.   
  40.             try {  
  41.                 socket = serverSocket.accept();  
  42.                 input = socket.getInputStream();  
  43.                 output = socket.getOutputStream();  
  44.                 Request request = new Request(input);  
  45.                 request.parse();  
  46.   
  47.                 Response response = new Response(output);  
  48.                 response.setRequest(request);  
  49.   
  50.                 // check if this is a request for a servlet or a static resource  
  51.                 if (request.getUri().startsWith("/servlet/")) {  
  52.                     ServletProcessor processor = new ServletProcessor();  
  53.                     processor.process(request, response);  
  54.                 } else {  
  55.                     StaticResourceProcessor processor = new StaticResourceProcessor();  
  56.                     processor.process(request, response);  
  57.                 }  
  58.   
  59.                 socket.close();  
  60.   
  61.                 shutdown = request.getUri().equals(SHUTDOWN_COMMAND);  
  62.             } catch (Exception e) {  
  63.                 e.printStackTrace();  
  64.                 continue;  
  65.             }  
  66.         }  
  67.     }  
  68. }  

  Request

Java代码   收藏代码
  1. package com.whatsmars.tomcat.servlet;  
  2.   
  3. import javax.servlet.*;  
  4. import java.io.BufferedReader;  
  5. import java.io.IOException;  
  6. import java.io.InputStream;  
  7. import java.io.UnsupportedEncodingException;  
  8. import java.util.Enumeration;  
  9. import java.util.Locale;  
  10. import java.util.Map;  
  11.   
  12. /** 
  13.  * Created by shenhongxi on 16/3/21. 
  14.  */  
  15. public class Request implements ServletRequest {  
  16.   
  17.     private InputStream input;  
  18.   
  19.     private String uri; // 性能考虑,用byte[]  
  20.   
  21.     public Request(InputStream input) {  
  22.         this.input = input;  
  23.     }  
  24.   
  25.     public void parse() {  
  26.         StringBuffer request = new StringBuffer(2048);  
  27.         int i;  
  28.         byte[] buffer = new byte[2048];  
  29.         try {  
  30.             i = input.read(buffer);  
  31.         } catch (IOException e) {  
  32.             e.printStackTrace();  
  33.             i = -1;  
  34.         }  
  35.         for (int j = 0; j < i; j++) {  
  36.             request.append((char) buffer[j]);  
  37.         }  
  38.         System.out.println(request.toString());  
  39.         uri = parseUri(request.toString());  
  40.     }  
  41.   
  42.     private String parseUri(String requestStr) {  
  43.         // GET /index.html HTTP/1.1  
  44.         // Accept: text/plain; text/html  
  45.         // ...  
  46.         int index1 = requestStr.indexOf(' ');  
  47.         int index2;  
  48.         if (index1 != -1) {  
  49.             index2 = requestStr.indexOf(' ', index1 + 1);  
  50.             if (index2 > index1) {  
  51.                 return requestStr.substring(index1 + 1, index2);  
  52.             }  
  53.         }  
  54.         return null;  
  55.     }  
  56.   
  57.     public String getUri() {  
  58.         return uri;  
  59.     }  
  60.   
  61.     public Object getAttribute(String name) {  
  62.         return null;  
  63.     }  
  64.   
  65.     public Enumeration<String> getAttributeNames() {  
  66.         return null;  
  67.     }  
  68.   
  69.     public String getCharacterEncoding() {  
  70.         return null;  
  71.     }  
  72.   
  73.     public void setCharacterEncoding(String env) throws UnsupportedEncodingException {  
  74.   
  75.     }  
  76.   
  77.     public int getContentLength() {  
  78.         return 0;  
  79.     }  
  80.   
  81. }  

 Response

Java代码   收藏代码
  1. package com.whatsmars.tomcat.servlet;  
  2.   
  3. import javax.servlet.ServletOutputStream;  
  4. import javax.servlet.ServletResponse;  
  5. import java.io.*;  
  6. import java.util.Locale;  
  7.   
  8. /** 
  9.  * Created by shenhongxi on 16/3/21. 
  10.  */  
  11. public class Response implements ServletResponse {  
  12.   
  13.     private static final int BUFFER_SIZE = 1024;  
  14.   
  15.     Request request;  
  16.   
  17.     OutputStream output;  
  18.   
  19.     PrintWriter writer;  
  20.   
  21.     public void sendStaticResource() throws IOException {  
  22.         byte[] bytes = new byte[BUFFER_SIZE];  
  23.         FileInputStream fis = null;  
  24.         try {  
  25.             File file = new File(Constants.WEB_ROOT, request.getUri());  
  26.             if (file.exists()) {  
  27.                 fis = new FileInputStream(file);  
  28.                 int ch = fis.read(bytes, 0, BUFFER_SIZE);  
  29.                 while (ch != -1) {  
  30.                     output.write(bytes, 0, ch);  
  31.                     ch = fis.read(bytes, 0, BUFFER_SIZE);  
  32.                 }  
  33.             } else {  
  34.                 String errorMsg = "HTTP/1.1 404 File Not Found\r\n" +  
  35.                         "Content-Type: text/html\r\n" +  
  36.                         "Content-Length: 23\r\n" +  
  37.                         "\r\n" +  
  38.                         "<h1>File Not Found</h1>";  
  39.                 output.write(errorMsg.getBytes());  
  40.             }  
  41.         } catch (Exception e) {  
  42.             e.printStackTrace();  
  43.         } finally {  
  44.             if (fis != null) {  
  45.                 fis.close();  
  46.             }  
  47.         }  
  48.     }  
  49.   
  50.     public Response(OutputStream output) {  
  51.         this.output = output;  
  52.     }  
  53.   
  54.     public void setRequest(Request request) {  
  55.         this.request = request;  
  56.     }  
  57.   
  58.     public String getCharacterEncoding() {  
  59.         return null;  
  60.     }  
  61.   
  62.     public String getContentType() {  
  63.         return null;  
  64.     }  
  65.   
  66.     public ServletOutputStream getOutputStream() throws IOException {  
  67.         return null;  
  68.     }  
  69.   
  70.     public PrintWriter getWriter() throws IOException {  
  71.         // autoflush is true, println() will flush, but print() will not  
  72.         writer = new PrintWriter(output, true);  
  73.         return writer;  
  74.     }  
  75.   
  76. }  

 RequestFacade

Java代码   收藏代码
  1. package com.whatsmars.tomcat.servlet;  
  2.   
  3. import javax.servlet.*;  
  4. import java.io.BufferedReader;  
  5. import java.io.IOException;  
  6. import java.io.UnsupportedEncodingException;  
  7. import java.util.Enumeration;  
  8. import java.util.Locale;  
  9. import java.util.Map;  
  10.   
  11. /** 
  12.  * Created by shenhongxi on 2016/4/12. 
  13.  */  
  14. public class RequestFacade implements ServletRequest {  
  15.   
  16.     private ServletRequest request;  
  17.   
  18.     public RequestFacade(Request request) {  
  19.         this.request = request;  
  20.     }  
  21.   
  22.     public Object getAttribute(String name) {  
  23.         return request.getAttribute(name);  
  24.     }  
  25.   
  26.     public Enumeration<String> getAttributeNames() {  
  27.         return request.getAttributeNames();  
  28.     }  
  29.   
  30. }  

 ResponseFacade

Java代码   收藏代码
  1. package com.whatsmars.tomcat.servlet;  
  2.   
  3. import javax.servlet.ServletOutputStream;  
  4. import javax.servlet.ServletResponse;  
  5. import java.io.IOException;  
  6. import java.io.PrintWriter;  
  7. import java.util.Locale;  
  8.   
  9. /** 
  10.  * Created by shenhongxi on 2016/4/12. 
  11.  */  
  12. public class ResponseFacade implements ServletResponse {  
  13.   
  14.     private ServletResponse response;  
  15.   
  16.     public ResponseFacade(Response response) {  
  17.         this.response = response;  
  18.     }  
  19.   
  20.     public String getCharacterEncoding() {  
  21.         return response.getCharacterEncoding();  
  22.     }  
  23.   
  24.     public String getContentType() {  
  25.         return null;  
  26.     }  
  27.   
  28.     public ServletOutputStream getOutputStream() throws IOException {  
  29.         return null;  
  30.     }  
  31.   
  32.     public PrintWriter getWriter() throws IOException {  
  33.         return response.getWriter();  
  34.     }  
  35.   
  36. }  

 ServletProcessor

Java代码   收藏代码
  1. package com.whatsmars.tomcat.servlet;  
  2.   
  3. import javax.servlet.Servlet;  
  4. import javax.servlet.ServletRequest;  
  5. import javax.servlet.ServletResponse;  
  6. import java.io.File;  
  7. import java.io.IOException;  
  8. import java.net.URL;  
  9. import java.net.URLClassLoader;  
  10. import java.net.URLStreamHandler;  
  11.   
  12. /** 
  13.  * Created by shenhongxi on 2016/4/12. 
  14.  */  
  15. public class ServletProcessor {  
  16.   
  17.     public void process(Request request, Response response) {  
  18.         String uri = request.getUri();  
  19.         String servletName = uri.substring(uri.lastIndexOf("/") + 1);  
  20.         URLClassLoader loader = null;  
  21.         try {  
  22.             URL[] urls = new URL[1];  
  23.             URLStreamHandler streamHandler = null;  
  24.             File classPath = new File(Constants.WEB_ROOT);  
  25.             String repository = (new URL("file"null, classPath.getCanonicalPath()  
  26.             + File.separator)).toString();  
  27.             urls[0] = new URL(null, repository, streamHandler);  
  28.             loader = new URLClassLoader(urls);  
  29.         } catch (IOException E) {  
  30.             E.printStackTrace();  
  31.         }  
  32.   
  33.         Class myClass = null;  
  34.         try {  
  35.             myClass = loader.loadClass(servletName);  
  36.         } catch (ClassNotFoundException e) {  
  37.             e.printStackTrace();  
  38.         }  
  39.   
  40.         Servlet servlet = null;  
  41.         try {  
  42.             servlet = (Servlet) myClass.newInstance();  
  43.             RequestFacade requestFacade = new RequestFacade(request);  
  44.             ResponseFacade responseFacade = new ResponseFacade(response);  
  45.             // 为了安全考虑,除了实现ServletRequest/ServletResponse的方法,  
  46.             // Request/Response中的其他公共方法需对servlet隐藏,所以用外观类  
  47.             servlet.service((ServletRequest) requestFacade, (ServletResponse) responseFacade);  
  48.         } catch (Exception e) {  
  49.             e.printStackTrace();  
  50.         } catch (Throwable e) {  
  51.             e.printStackTrace();  
  52.         }  
  53.     }  
  54. }  

 StaticResourceProcessor

Java代码   收藏代码
  1. package com.whatsmars.tomcat.servlet;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. /** 
  6.  * Created by shenhongxi on 2016/4/12. 
  7.  */  
  8. public class StaticResourceProcessor {  
  9.   
  10.     public void process(Request request, Response response) {  
  11.         try {  
  12.             response.sendStaticResource();  
  13.         } catch (IOException e) {  
  14.             e.printStackTrace();  
  15.         }  
  16.     }  
  17. }  

  PrimitiveServlet

Java代码   收藏代码
  1. package com.whatsmars.tomcat.servlet;  
  2.   
  3. import javax.servlet.*;  
  4. import java.io.IOException;  
  5. import java.io.PrintWriter;  
  6.   
  7. /** 
  8.  * Created by shenhongxi on 2016/4/12. 
  9.  */  
  10. public class PrimitiveServlet implements Servlet {  
  11.     public void init(ServletConfig config) throws ServletException {  
  12.         System.out.println("init");  
  13.     }  
  14.   
  15.     public ServletConfig getServletConfig() {  
  16.         return null;  
  17.     }  
  18.   
  19.     public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {  
  20.         System.out.println("from service");  
  21.         PrintWriter out = res.getWriter();  
  22.         out.println("Hello. Roses are red.");  
  23.         out.print("Violets are blue");  
  24.     }  
  25.   
  26.     public String getServletInfo() {  
  27.         return null;  
  28.     }  
  29.   
  30.     public void destroy() {  
  31.         System.out.println("destroy");  
  32.     }  
  33. }  

  Constants

Java代码   收藏代码
  1. package com.whatsmars.tomcat.servlet;  
  2.   
  3. import java.io.File;  
  4.   
  5. /** 
  6.  * Created by shenhongxi on 2016/4/12. 
  7.  */  
  8. public class Constants {  
  9.   
  10.     public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "whatsmars-tomcat/src/main/webapp"// 资源文件,class文件等  
  11. }  

 



原文链接:[http://wely.iteye.com/blog/2290575]

相关文章
|
6月前
|
Java 应用服务中间件 容器
25 SpringBoot使用外置的Servlet容器
25 SpringBoot使用外置的Servlet容器
23 0
|
6月前
|
前端开发 Java 应用服务中间件
24 SpringBoot配置嵌入式Servlet容器
24 SpringBoot配置嵌入式Servlet容器
38 0
24 SpringBoot配置嵌入式Servlet容器
|
Java 中间件 应用服务中间件
Web 容器、HTTP 服务器 、Servlet 容器区别与联系
Web 容器、HTTP 服务器 、Servlet 容器区别与联系
242 0
Web 容器、HTTP 服务器 、Servlet 容器区别与联系
|
设计模式 安全 Java
【Tomcat技术专题】循序渐进,分析Servlet容器鼻祖的Server和Service组件原理
【Tomcat技术专题】循序渐进,分析Servlet容器鼻祖的Server和Service组件原理
130 0
【Tomcat技术专题】循序渐进,分析Servlet容器鼻祖的Server和Service组件原理
|
前端开发 小程序 JavaScript
【JavaWeb】一文Servlet全解:继承关系、生命周期、容器和请求转发与重定向等
【JavaWeb】一文Servlet全解:继承关系、生命周期、容器和请求转发与重定向等
185 0
【JavaWeb】一文Servlet全解:继承关系、生命周期、容器和请求转发与重定向等
|
前端开发 Java 应用服务中间件
Spring 全家桶之 Spring Boot 2.6.4(八)- 嵌入式 Servlet 容器(Part B)
Spring 全家桶之 Spring Boot 2.6.4(八)- 嵌入式 Servlet 容器(Part B)
Spring 全家桶之 Spring Boot 2.6.4(八)- 嵌入式 Servlet 容器(Part B)
|
前端开发 Java 应用服务中间件
Spring 全家桶之 Spring Boot 2.6.4(八)- 嵌入式 Servlet 容器(Part A)
Spring 全家桶之 Spring Boot 2.6.4(八)- 嵌入式 Servlet 容器(Part A)
Spring 全家桶之 Spring Boot 2.6.4(八)- 嵌入式 Servlet 容器(Part A)
|
Java 应用服务中间件 开发者
外部 Servlet 容器启动|学习笔记
快速学习外部 Servlet 容器启动
96 0
|
Java 应用服务中间件 开发者
使用外部 Servlet 容器 &amp;JSP 支持|学习笔记
快速学习使用外部 Servlet 容器&amp;JSP 支持
139 0
切换其他嵌入式 Servlet 容器|学习笔记
快速学习切换其他嵌入式 Servlet 容器
62 0
切换其他嵌入式 Servlet 容器|学习笔记