`
VerRan
  • 浏览: 456920 次
  • 性别: Icon_minigender_1
  • 来自: 陕西.西安
社区版块
存档分类
最新评论

简单的servlet容器实现

阅读更多
1. HttpServer1
  1. package ex02.pyrmont;   
  2.   
  3. import java.net.Socket;   
  4. import java.net.ServerSocket;   
  5. import java.net.InetAddress;   
  6. import java.io.InputStream;   
  7. import java.io.OutputStream;   
  8. import java.io.IOException;   
  9.   
  10. public class HttpServer1 {   
  11.   
  12.   /** WEB_ROOT is the directory where our HTML and other files reside.  
  13.    *  For this package, WEB_ROOT is the "webroot" directory under the working  
  14.    *  directory.  
  15.    *  The working directory is the location in the file system  
  16.    *  from where the java command was invoked.  
  17.    */  
  18.   // shutdown command   
  19.   private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";   
  20.   
  21.   // the shutdown command received   
  22.   private boolean shutdown = false;   
  23.   
  24.   public static void main(String[] args) {   
  25.     HttpServer1 server = new HttpServer1();   
  26.     server.await();   
  27.   }   
  28.   
  29.   public void await() {   
  30.     ServerSocket serverSocket = null;   
  31.     int port = 8080;   
  32.     try {   
  33.       serverSocket =  new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));   
  34.     }   
  35.     catch (IOException e) {   
  36.       e.printStackTrace();   
  37.       System.exit(1);   
  38.     }   
  39.   
  40.     // Loop waiting for a request   
  41.     while (!shutdown) {   
  42.       Socket socket = null;   
  43.       InputStream input = null;   
  44.       OutputStream output = null;   
  45.       try {   
  46.         socket = serverSocket.accept();   
  47.         input = socket.getInputStream();   
  48.         output = socket.getOutputStream();   
  49.   
  50.         // create Request object and parse   
  51.         Request request = new Request(input);   
  52.         request.parse();   
  53.   
  54.         // create Response object   
  55.         Response response = new Response(output);   
  56.         response.setRequest(request);   
  57.   
  58.         // check if this is a request for a servlet or a static resource   
  59.         // a request for a servlet begins with "/servlet/"   
  60.         if (request.getUri().startsWith("/servlet/")) {   
  61.           ServletProcessor1 processor = new ServletProcessor1();   
  62.           processor.process(request, response);   
  63.         }   
  64.         else {   
  65.           StaticResourceProcessor processor = new StaticResourceProcessor();   
  66.           processor.process(request, response);   
  67.         }   
  68.   
  69.         // Close the socket   
  70.         socket.close();   
  71.         //check if the previous URI is a shutdown command   
  72.         shutdown = request.getUri().equals(SHUTDOWN_COMMAND);   
  73.       }   
  74.       catch (Exception e) {   
  75.         e.printStackTrace();   
  76.         System.exit(1);   
  77.       }   
  78.     }   
  79.   }   
  80. }   

2. Request
java 代码
  1. package ex02.pyrmont;   
  2.   
  3. import java.io.InputStream;   
  4. import java.io.IOException;   
  5. import java.io.BufferedReader;   
  6. import java.io.UnsupportedEncodingException;   
  7. import java.util.Enumeration;   
  8. import java.util.Locale;   
  9. import java.util.Map;   
  10. import javax.servlet.RequestDispatcher;   
  11. import javax.servlet.ServletInputStream;   
  12. import javax.servlet.ServletRequest;   
  13.   
  14.   
  15. public class Request implements ServletRequest {   
  16.   
  17.   private InputStream input;   
  18.   private String uri;   
  19.   
  20.   public Request(InputStream input) {   
  21.     this.input = input;   
  22.   }   
  23.   
  24.   public String getUri() {   
  25.     return uri;   
  26.   }   
  27.   
  28.   private String parseUri(String requestString) {   
  29.     int index1, index2;   
  30.     index1 = requestString.indexOf(' ');   
  31.     if (index1 != -1) {   
  32.       index2 = requestString.indexOf(' ', index1 + 1);   
  33.       if (index2 > index1)   
  34.         return requestString.substring(index1 + 1, index2);   
  35.     }   
  36.     return null;   
  37.   }   
  38.   
  39.   public void parse() {   
  40.     // Read a set of characters from the socket   
  41.     StringBuffer request = new StringBuffer(2048);   
  42.     int i;   
  43.     byte[] buffer = new byte[2048];   
  44.     try {   
  45.       i = input.read(buffer);   
  46.     }   
  47.     catch (IOException e) {   
  48.       e.printStackTrace();   
  49.       i = -1;   
  50.     }   
  51.     for (int j=0; j
  52.       request.append((char) buffer[j]);   
  53.     }   
  54.     System.out.print(request.toString());   
  55.     uri = parseUri(request.toString());   
  56.   }   
  57.   
  58.   /* implementation of the ServletRequest*/  
  59.   public Object getAttribute(String attribute) {   
  60.     return null;   
  61.   }   
  62.   
  63.   public Enumeration getAttributeNames() {   
  64.     return null;   
  65.   }   
  66.   
  67.   public String getRealPath(String path) {   
  68.     return null;   
  69.   }   
  70.   
  71.   public RequestDispatcher getRequestDispatcher(String path) {   
  72.     return null;   
  73.   }   
  74.   
  75.   public boolean isSecure() {   
  76.     return false;   
  77.   }   
  78.   
  79.   public String getCharacterEncoding() {   
  80.     return null;   
  81.   }   
  82.   
  83.   public int getContentLength() {   
  84.     return 0;   
  85.   }   
  86.   
  87.   public String getContentType() {   
  88.     return null;   
  89.   }   
  90.   
  91.   public ServletInputStream getInputStream() throws IOException {   
  92.     return null;   
  93.   }   
  94.   
  95.   public Locale getLocale() {   
  96.     return null;   
  97.   }   
  98.   
  99.   public Enumeration getLocales() {   
  100.     return null;   
  101.   }   
  102.   
  103.   public String getParameter(String name) {   
  104.     return null;   
  105.   }   
  106.   
  107.   public Map getParameterMap() {   
  108.     return null;   
  109.   }   
  110.   
  111.   public Enumeration getParameterNames() {   
  112.     return null;   
  113.   }   
  114.   
  115.   public String[] getParameterValues(String parameter) {   
  116.     return null;   
  117.   }   
  118.   
  119.   public String getProtocol() {   
  120.     return null;   
  121.   }   
  122.   
  123.   public BufferedReader getReader() throws IOException {   
  124.     return null;   
  125.   }   
  126.   
  127.   public String getRemoteAddr() {   
  128.     return null;   
  129.   }   
  130.   
  131.   public String getRemoteHost() {   
  132.     return null;   
  133.   }   
  134.   
  135.   public String getScheme() {   
  136.    return null;   
  137.   }   
  138.   
  139.   public String getServerName() {   
  140.     return null;   
  141.   }   
  142.   
  143.   public int getServerPort() {   
  144.     return 0;   
  145.   }   
  146.   
  147.   public void removeAttribute(String attribute) {   
  148.   }   
  149.   
  150.   public void setAttribute(String key, Object value) {   
  151.   }   
  152.   
  153.   public void setCharacterEncoding(String encoding)   
  154.     throws UnsupportedEncodingException {   
  155.   }   
  156.   
  157. }  

3. response
java 代码
  1. package ex02.pyrmont;   
  2.   
  3. import java.io.OutputStream;   
  4. import java.io.IOException;   
  5. import java.io.FileInputStream;   
  6. import java.io.FileNotFoundException;   
  7. import java.io.File;   
  8. import java.io.PrintWriter;   
  9. import java.util.Locale;   
  10. import javax.servlet.ServletResponse;   
  11. import javax.servlet.ServletOutputStream;   
  12.   
  13. public class Response implements ServletResponse {   
  14.   
  15.   private static final int BUFFER_SIZE = 1024;   
  16.   Request request;   
  17.   OutputStream output;   
  18.   PrintWriter writer;   
  19.   
  20.   public Response(OutputStream output) {   
  21.     this.output = output;   
  22.   }   
  23.   
  24.   public void setRequest(Request request) {   
  25.     this.request = request;   
  26.   }   
  27.   
  28.   /* This method is used to serve a static page */  
  29.   public void sendStaticResource() throws IOException {   
  30.     byte[] bytes = new byte[BUFFER_SIZE];   
  31.     FileInputStream fis = null;   
  32.     try {   
  33.       /* request.getUri has been replaced by request.getRequestURI */  
  34.       File file = new File(Constants.WEB_ROOT, request.getUri());   
  35.       fis = new FileInputStream(file);   
  36.       /*  
  37.          HTTP Response = Status-Line  
  38.            *(( general-header | response-header | entity-header ) CRLF)  
  39.            CRLF  
  40.            [ message-body ]  
  41.          Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF  
  42.       */  
  43.       int ch = fis.read(bytes, 0, BUFFER_SIZE);   
  44.       while (ch!=-1) {   
  45.         output.write(bytes, 0, ch);   
  46.         ch = fis.read(bytes, 0, BUFFER_SIZE);   
  47.       }   
  48.     }   
  49.     catch (FileNotFoundException e) {   
  50.       String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +   
  51.         "Content-Type: text/html\r\n" +   
  52.         "Content-Length: 23\r\n" +   
  53.         "\r\n" +   
  54.         "

    File Not Found

    "
    ;   
  55.       output.write(errorMessage.getBytes());   
  56.     }   
  57.     finally {   
  58.       if (fis!=null)   
  59.         fis.close();   
  60.     }   
  61.   }   
  62.   
  63.   
  64.   /** implementation of ServletResponse  */  
  65.   public void flushBuffer() throws IOException {   
  66.   }   
  67.   
  68.   public int getBufferSize() {   
  69.     return 0;   
  70.   }   
  71.   
  72.   public String getCharacterEncoding() {   
  73.     return null;   
  74.   }   
  75.   
  76.   public Locale getLocale() {   
  77.     return null;   
  78.   }   
  79.   
  80.   public ServletOutputStream getOutputStream() throws IOException {   
  81.     return null;   
  82.   }   
  83.   
  84.   public PrintWriter getWriter() throws IOException {   
  85.     // autoflush is true, println() will flush,   
  86.     // but print() will not.   
  87.     writer = new PrintWriter(output, true);   
  88.     return writer;   
  89.   }   
  90.   
  91.   public boolean isCommitted() {   
  92.     return false;   
  93.   }   
  94.   
  95.   public void reset() {   
  96.   }   
  97.   
  98.   public void resetBuffer() {   
  99.   }   
  100.   
  101.   public void setBufferSize(int size) {   
  102.   }   
  103.   
  104.   public void setContentLength(int length) {   
  105.   }   
  106.   
  107.   public void setContentType(String type) {   
  108.   }   
  109.   
  110.   public void setLocale(Locale locale) {   
  111.   }   
  112. }  

4. 用于处理servlet的类ServletProcessor1
java 代码
  1. package ex02.pyrmont;   
  2.   
  3. import java.net.URL;   
  4. import java.net.URLClassLoader;   
  5. import java.net.URLStreamHandler;   
  6. import java.io.File;   
  7. import java.io.IOException;   
  8. import javax.servlet.Servlet;   
  9. import javax.servlet.ServletRequest;   
  10. import javax.servlet.ServletResponse;   
  11.   
  12. public class ServletProcessor1 {   
  13.   
  14.   public void process(Request request, Response response) {   
  15.   
  16.     String uri = request.getUri();   
  17.     String servletName = uri.substring(uri.lastIndexOf("/") + 1);   
  18.     URLClassLoader loader = null;   
  19.   
  20.     try {   
  21.       // create a URLClassLoader   
  22.       URL[] urls = new URL[1];   
  23.       URLStreamHandler streamHandler = null;   
  24.       File classPath = new File(Constants.WEB_ROOT);   
  25.       // the forming of repository is taken from the createClassLoader method in   
  26.       // org.apache.catalina.startup.ClassLoaderFactory   
  27.       String repository = (new URL("file"null, classPath.getCanonicalPath() + File.separator)).toString() ;   
  28.       // the code for forming the URL is taken from the addRepository method in   
  29.       // org.apache.catalina.loader.StandardClassLoader class.   
  30.       urls[0] = new URL(null, repository, streamHandler);   
  31.       loader = new URLClassLoader(urls);   
  32.     }   
  33.     catch (IOException e) {   
  34.       System.out.println(e.toString() );   
  35.     }   
  36.     Class myClass = null;   
  37.     try {   
  38.       myClass = loader.loadClass(servletName);   
  39.     }   
  40.     catch (ClassNotFoundException e) {   
  41.       System.out.println(e.toString());   
  42.     }   
  43.   
  44.     Servlet servlet = null;   
  45.   
  46.     try {   
  47.       servlet = (Servlet) myClass.newInstance();   
  48.       servlet.service((ServletRequest) request, (ServletResponse) response);   
  49.     }   
  50.     catch (Exception e) {   
  51.       System.out.println(e.toString());   
  52.     }   
  53.     catch (Throwable e) {   
  54.       System.out.println(e.toString());   
  55.     }   
  56.   
  57.   }   
  58. }  


 5.处理静态资源的类

java 代码
  1. package ex02.pyrmont;   
  2.   
  3. import java.io.IOException;   
  4.   
  5. public class StaticResourceProcessor {   
  6.   
  7.   public void process(Request request, Response response) {   
  8.     try {   
  9.       response.sendStaticResource();   
  10.     }   
  11.     catch (IOException e) {   
  12.       e.printStackTrace();   
  13.     }   
  14.   }   
  15. }  


6. 用于测试的servlet

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


这个servlet服务器是一个很简单的实现,只能处理很简单的功能,比如将字符创输出到网页上。。
ServletProcessor1类实现了利用自建的ClassLoader加载自己的servlet,然后实例化这个servlet实现他的service方法。。

分享到:
评论

相关推荐

    一个简单的servlet容器

    本主题将深入探讨“一个简单的Servlet容器”的实现,参考自《深入剖析Tomcat》这本书的第二章。 Servlet容器的主要职责是接收HTTP请求,然后调用相应的Servlet来处理这些请求,并将Servlet的响应返回给客户端。在...

    servlet基础与servlet容器模型

    Servlet容器通过实现Servlet API来与Servlet交互,提供了Web应用部署、安全控制、会话管理等高级功能。 Servlet容器模型通常包含以下组件: 1. **Web应用**:一组相关的资源(HTML、CSS、JavaScript、图片、...

    servlet容器工作原理

    在讨论Servlet容器的具体实现之前,我们先来看看构成Servlet容器的关键组件。 1. **Servlet容器本身**:负责处理HTTP请求、管理Servlet实例等。 2. **Servlet实例**:实际处理客户端请求的组件。 3. **Servlet配置*...

    SpringBoot之配置嵌入式Servlet容器.pdf

    嵌入式Servlet容器是SpringBoot中的重要组件,能够将Web服务器(例如Tomcat、Jetty或Undertow)嵌入到应用程序的内部运行,使得部署更为简单便捷。接下来我们将根据给定的文件内容,深入探讨SpringBoot配置嵌入式...

    Servlet 容器工作原理解析

    Servlet容器是Java Web技术的核心组成部分,它为Servlet提供运行环境,使得开发者无需关注底层细节,专注于业务逻辑的实现。本文以Tomcat为例,深入解析Servlet容器的工作原理。 首先,Servlet容器,如Tomcat,是一...

    Servlet容器工作原理讲解

    更复杂的Servlet容器,如Tomcat 4和5,其内部实现涉及多线程、网络通信、容器管理策略等多个方面,这些内容在《TOMCAT 运行内幕》等书籍中有详细介绍。 总之,Servlet容器是Java Web应用的核心组件,它负责管理和...

    JAVA WEB中Servlet和Servlet容器的区别

    "JAVA WEB中Servlet和Servlet容器的区别" 在 Java Web 开发中,Servlet 和 Servlet 容器是两个非常重要的概念,但是很多人对它们的区别却不甚了解。本文将对 Servlet 和 Servlet 容器进行详细的介绍,并阐述它们...

    Jetty 9 Servlet容器

    Jetty 9是一款轻量级、高性能且开源的Servlet容器,它主要负责处理基于Java Servlet规范的应用程序。作为Java服务的一部分,Jetty9为开发者提供了高效、稳定且灵活的平台来部署和运行Web应用程序。 首先,Jetty 9...

    Servlet实现简单购物车

    【Servlet实现简单购物车】 Servlet是Java Web开发中的一个核心组件,主要用于处理HTTP请求和响应。在本项目中,"Servlet实现简单购物车"是指利用Servlet技术来构建一个基础的在线购物车系统。这个系统可能包括添加...

    jetty轻量级servlet容器

    Jetty 是一个用 Java 实现、开源、基于标准的,并且具有丰富功能的 Http 服务器和 Web 容器,可以免费的用于商业行为。Jetty 这个项目成立于 1995 年,现在已经有非常多的成功产品基于 Jetty,比如 Apache Geromino...

    Servlet容器在请求对象中设置的属性

    在源码层面,我们可以深入研究Servlet容器如何实现这些功能。通常,Servlet容器会维护一个属性映射表,当调用`setAttribute()`时,它会在表中添加键值对。同时,`getAttribute()`则会根据给定的键从表中查找并返回...

    CKEditor 上传文件(Servlet实现)

    - 要确保Servlet容器(如Tomcat)已经配置了Servlet的映射,例如在web.xml中添加如下配置: ```xml <servlet> <servlet-name>UploadServlet</servlet-name> <servlet-class>...

    利用servlet监听器,系统启动时创建自定义容器简单例子

    在"利用servlet监听器,系统启动时创建自定义容器简单例子"中,我们主要关注`ServletContextListener`接口。要创建一个监听器,你需要编写一个类,实现`ServletContextListener`接口,并重写它的两个方法:`context...

    JSP+Servlet实现简易购物车功能

    6. **Web容器**:为了运行JSP和Servlet,我们需要一个支持Java EE的Web容器,如Tomcat,它可以解析JSP页面并执行Servlet。 7. **项目结构**:ShopCart这个文件夹可能包含了JSP文件、Servlet类、配置文件(如web.xml...

    Servlet项目实践 实现学生信息系统的全部代码

     按照一种约定俗成的称呼习惯,通常我们也把实现了servlet接口的java程序,称之为Servlet 二、Servlet的运行过程 Servlet程序是由WEB服务器调用,web服务器收到客户端的Servlet访问请求后:  ①Web服务器首先检查...

    Tomcat(全称为Apache Tomcat)是一个开源的Java Servlet容器,由Apache软件基金会下属的Jaka

    tomcatTomcat(全称为Apache Tomcat)是一个开源的Java Servlet容器,由Apache软件基金会下属的Jakarta项目开发。Tomcat实现了Java Servlet、JavaServer Pages(JSP)和Java Expression Language(EL)等Java技术,...

Global site tag (gtag.js) - Google Analytics