HttpServer
package com.whatsmars.tomcat.servlet; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; /** * Created by shenhongxi on 16/3/21. */ 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(); } private void await() { ServerSocket serverSocket = null; int port = 8080; try { serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1")); System.out.println("Server started!"); } 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); // check if this is a request for a servlet or a static resource if (request.getUri().startsWith("/servlet/")) { ServletProcessor processor = new ServletProcessor(); 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; } } } }
Request
package com.whatsmars.tomcat.servlet; import javax.servlet.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.Enumeration; import java.util.Locale; import java.util.Map; /** * Created by shenhongxi on 16/3/21. */ public class Request implements ServletRequest { private InputStream input; private String uri; // 性能考虑,用byte[] public Request(InputStream input) { this.input = input; } public 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.println(request.toString()); uri = parseUri(request.toString()); } private String parseUri(String requestStr) { // GET /index.html HTTP/1.1 // Accept: text/plain; text/html // ... int index1 = requestStr.indexOf(' '); int index2; if (index1 != -1) { index2 = requestStr.indexOf(' ', index1 + 1); if (index2 > index1) { return requestStr.substring(index1 + 1, index2); } } return null; } public String getUri() { return uri; } public Object getAttribute(String name) { return null; } public Enumeration<String> getAttributeNames() { return null; } public String getCharacterEncoding() { return null; } public void setCharacterEncoding(String env) throws UnsupportedEncodingException { } public int getContentLength() { return 0; } }
Response
package com.whatsmars.tomcat.servlet; import javax.servlet.ServletOutputStream; import javax.servlet.ServletResponse; import java.io.*; import java.util.Locale; /** * Created by shenhongxi on 16/3/21. */ public class Response implements ServletResponse { private static final int BUFFER_SIZE = 1024; Request request; OutputStream output; PrintWriter writer; public 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); while (ch != -1) { output.write(bytes, 0, ch); ch = fis.read(bytes, 0, BUFFER_SIZE); } } else { String errorMsg = "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(errorMsg.getBytes()); } } catch (Exception e) { e.printStackTrace(); } finally { if (fis != null) { fis.close(); } } } public Response(OutputStream output) { this.output = output; } public void setRequest(Request request) { this.request = request; } public String getCharacterEncoding() { return null; } public String getContentType() { return null; } public ServletOutputStream getOutputStream() throws IOException { return null; } public PrintWriter getWriter() throws IOException { // autoflush is true, println() will flush, but print() will not writer = new PrintWriter(output, true); return writer; } }
RequestFacade
package com.whatsmars.tomcat.servlet; import javax.servlet.*; import java.io.BufferedReader; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Enumeration; import java.util.Locale; import java.util.Map; /** * Created by shenhongxi on 2016/4/12. */ public class RequestFacade implements ServletRequest { private ServletRequest request; public RequestFacade(Request request) { this.request = request; } public Object getAttribute(String name) { return request.getAttribute(name); } public Enumeration<String> getAttributeNames() { return request.getAttributeNames(); } }
ResponseFacade
package com.whatsmars.tomcat.servlet; import javax.servlet.ServletOutputStream; import javax.servlet.ServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Locale; /** * Created by shenhongxi on 2016/4/12. */ public class ResponseFacade implements ServletResponse { private ServletResponse response; public ResponseFacade(Response response) { this.response = response; } public String getCharacterEncoding() { return response.getCharacterEncoding(); } public String getContentType() { return null; } public ServletOutputStream getOutputStream() throws IOException { return null; } public PrintWriter getWriter() throws IOException { return response.getWriter(); } }
ServletProcessor
package com.whatsmars.tomcat.servlet; import javax.servlet.Servlet; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.io.File; import java.io.IOException; import java.net.URL; import java.net.URLClassLoader; import java.net.URLStreamHandler; /** * Created by shenhongxi on 2016/4/12. */ public class ServletProcessor { 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 streamHandler = 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, streamHandler); loader = new URLClassLoader(urls); } catch (IOException E) { E.printStackTrace(); } Class myClass = null; try { myClass = loader.loadClass(servletName); } catch (ClassNotFoundException e) { e.printStackTrace(); } Servlet servlet = null; try { servlet = (Servlet) myClass.newInstance(); RequestFacade requestFacade = new RequestFacade(request); ResponseFacade responseFacade = new ResponseFacade(response); // 为了安全考虑,除了实现ServletRequest/ServletResponse的方法, // Request/Response中的其他公共方法需对servlet隐藏,所以用外观类 servlet.service((ServletRequest) requestFacade, (ServletResponse) responseFacade); } catch (Exception e) { e.printStackTrace(); } catch (Throwable e) { e.printStackTrace(); } } }
StaticResourceProcessor
package com.whatsmars.tomcat.servlet; import java.io.IOException; /** * Created by shenhongxi on 2016/4/12. */ public class StaticResourceProcessor { public void process(Request request, Response response) { try { response.sendStaticResource(); } catch (IOException e) { e.printStackTrace(); } } }
PrimitiveServlet
package com.whatsmars.tomcat.servlet; import javax.servlet.*; import java.io.IOException; import java.io.PrintWriter; /** * Created by shenhongxi on 2016/4/12. */ public class PrimitiveServlet implements Servlet { public void init(ServletConfig config) throws ServletException { System.out.println("init"); } public ServletConfig getServletConfig() { return null; } public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { System.out.println("from service"); PrintWriter out = res.getWriter(); out.println("Hello. Roses are red."); out.print("Violets are blue"); } public String getServletInfo() { return null; } public void destroy() { System.out.println("destroy"); } }
Constants
package com.whatsmars.tomcat.servlet; import java.io.File; /** * Created by shenhongxi on 2016/4/12. */ public class Constants { public static final String WEB_ROOT = System.getProperty("user.dir") + File.separator + "whatsmars-tomcat/src/main/webapp"; // 资源文件,class文件等 }
相关推荐
这个简单的Servlet容器没有实现多线程,这意味着每次只能处理一个请求。在实际的Servlet容器如Tomcat或Jetty中,每个请求通常会在单独的线程中处理,以支持高并发。 总结起来,这个简单的Servlet容器示例展示了如何...
- Servlet容器为每个定义的Servlet创建一个实例,并调用其`init()`方法进行初始化。在此过程中,Servlet可以进行必要的准备工作,如建立数据库连接或加载配置文件。 - `init()`方法通常被覆盖以执行特定于应用的...
Tomcat是一个开源、轻量级的Servlet容器,由Apache软件基金会维护。本项目基于《深入剖析Tomcat》一书中的第二章代码,进行了相应修改,旨在帮助开发者更深入地理解和运用Servlet容器。 首先,Servlet是Java平台上...
Tomcat是Apache下的一个开源项目,其作为Servlet容器和JSP引擎,广泛应用于小型和中等规模的Web应用。SpringBoot通过自动配置机制简化了Tomcat的配置,而开发者也可以根据需要进行修改和扩展。 要修改SpringBoot的...
3. **Resin**:由Caucho公司开发,也是一个强大的Servlet容器,特别适合处理高并发请求。Resin的部署方式也包括将Web应用的目录结构放入其指定的webapps目录。 在Servlet容器中,Servlet生命周期包括加载、初始化、...
下面是一个简单的Servlet示例,即`PrimitiveServlet`,它实现了Servlet接口并打印出调用的方法名: ```java public class PrimitiveServlet implements Servlet { public void init(ServletConfig config) throws ...
本章讨论了构建一个简单Servlet容器所需的关键概念和技术细节。 - **简述**:概述了Servlet容器的作用和基本组成。 - **javax.servlet.Servlet接口**:介绍了Servlet接口的定义及其核心方法。 - **Application1**:...
在这个例子中,我们将探讨如何利用Servlet监听器在系统启动时创建一个自定义容器。 首先,我们需要了解Servlet监听器的概念。Servlet监听器是实现了Java Servlet API中特定接口的类,这些接口定义了对Web应用生命...
在这个"简单的servlet例子"中,我们将深入理解如何创建一个基础的Servlet以及如何配置它在Web应用程序中运行。 1. **Servlet接口与实现** `mybasicservlet` 类实现了`Servlet`接口。`Servlet`接口定义了Servlet的...
### 简单Servlet开发详解 #### 一、实验目的 在本次实验中,我们将学习如何使用Eclipse IDE来开发并测试几个简单的Servlet程序。通过本实验,学生能够更深入地理解Servlet的工作原理,掌握其开发流程,并进一步...
以下是一个简单的Servlet示例: ```java import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class MyServlet extends HttpServlet { protected void doGet(HttpServletRequest ...
注意,这里的Servlet容器还非常基础,没有实现Servlet的生命周期管理(如单例或多例模式)、多线程安全、部署描述符解析等功能,这些都是成熟的Servlet容器(如Tomcat、Jetty等)会提供的高级特性。在实际开发中,...
在本"最简单的Servlet应用DEMO下载"中,我们将深入理解Servlet的基本概念、工作原理以及如何创建和运行一个简单的Servlet应用程序。 一、Servlet基本概念 Servlet是一种服务器端的Java小程序,它可以扩展服务器的...
"简单迅速的web容器"可能指的是一个轻量级、快速启动且易于部署的Web服务器解决方案,适合小型项目或开发测试环境。 在提供的文件列表中,我们有以下几个关键文件: 1. **EasyWebSvr.exe**:这很可能是一个可执行...
在本项目中,"Servlet实现简单购物车"是指利用Servlet技术来构建一个基础的在线购物车系统。这个系统可能包括添加商品到购物车、查看购物车内容、修改商品数量以及清空购物车等功能。 首先,我们需要了解Servlet的...
1. 创建一个简单的Servlet,处理GET请求并返回欢迎消息。 2. 学习如何通过Servlet传递参数,并在Servlet中处理这些参数。 3. 理解Servlet的生命周期,模拟Servlet的初始化和销毁过程。 4. 配置Servlet,尝试不同的...
在本文中,我们将深入探讨如何使用Servlet技术来构建一个简单的Web应用程序,该程序涵盖了注册、登录和主页面操作等功能。Servlet是一种Java编程接口,用于扩展服务器的功能,特别适合处理HTTP请求。在这里,我们...
Apache Tomcat是一款功能强大且广受欢迎的开源软件,它既是Java Servlet容器也是Web服务器。Tomcat能够运行Java代码,并全面支持Jakarta EE(原Java EE)技术栈中的关键组件,包括Servlets和JSP(JavaServer Pages)...