1. package ex02.pyrmont1;
  2.  
  3. import java.io.File;
  4.  
  5. public class Constants {
  6. public static final String WEB_ROOT =
  7. System.getProperty("user.dir") + File.separator + "webroot";
  8. }
  1. package ex02.pyrmont1;
  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 HttpServer2 {
  11.  
  12. // shutdown command
  13. private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
  14.  
  15. // the shutdown command received
  16. private boolean shutdown = false;
  17.  
  18. public static void main(String[] args) {
  19. HttpServer2 server = new HttpServer2();
  20. server.await();
  21. }
  22.  
  23. public void await() {
  24. ServerSocket serverSocket = null;
  25. int port = 8080;
  26. try {
  27. serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
  28. }
  29. catch (IOException e) {
  30. e.printStackTrace();
  31. System.exit(1);
  32. }
  33.  
  34. // Loop waiting for a request
  35. while (!shutdown) {
  36. Socket socket = null;
  37. InputStream input = null;
  38. OutputStream output = null;
  39. try {
  40. socket = serverSocket.accept();
  41. input = socket.getInputStream();
  42. output = socket.getOutputStream();
  43.  
  44. // create Request object and parse
  45. Request request = new Request(input);
  46. request.parse();
  47.  
  48. // create Response object
  49. Response response = new Response(output);
  50. response.setRequest(request);
  51.  
  52. //check if this is a request for a servlet or a static resource
  53. //a request for a servlet begins with "/servlet/"
  54. if (request.getUri().startsWith("/servlet/")) {
  55. ServletProcessor2 processor = new ServletProcessor2();
  56. processor.process(request, response);
  57. }
  58. else {
  59. StaticResourceProcessor processor = new StaticResourceProcessor();
  60. processor.process(request, response);
  61. }
  62.  
  63. // Close the socket
  64. socket.close();
  65. //check if the previous URI is a shutdown command
  66. shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
  67. }
  68. catch (Exception e) {
  69. e.printStackTrace();
  70. System.exit(1);
  71. }
  72. }
  73. }
  74. }
  1. package ex02.pyrmont1;
  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. public class Request implements ServletRequest {
  15.  
  16. private InputStream input;
  17. private String uri;
  18.  
  19. public Request(InputStream input) {
  20. this.input = input;
  21. }
  22.  
  23. public String getUri() {
  24. return uri;
  25. }
  26.  
  27. private String parseUri(String requestString) {
  28. int index1, index2;
  29. index1 = requestString.indexOf(' ');
  30. if (index1 != -1) {
  31. index2 = requestString.indexOf(' ', index1 + 1);
  32. if (index2 > index1)
  33. return requestString.substring(index1 + 1, index2);
  34. }
  35. return null;
  36. }
  37.  
  38. public void parse() {
  39. // Read a set of characters from the socket
  40. StringBuffer request = new StringBuffer(2048);
  41. int i;
  42. byte[] buffer = new byte[2048];
  43. try {
  44. i = input.read(buffer);
  45. }
  46. catch (IOException e) {
  47. e.printStackTrace();
  48. i = -1;
  49. }
  50. for (int j=0; j<i; j++) {
  51. request.append((char) buffer[j]);
  52. }
  53. System.out.print(request.toString());
  54. uri = parseUri(request.toString());
  55. }
  56.  
  57. /* implementation of the ServletRequest*/
  58. public Object getAttribute(String attribute) {
  59. return null;
  60. }
  61.  
  62. public Enumeration getAttributeNames() {
  63. return null;
  64. }
  65.  
  66. public String getRealPath(String path) {
  67. return null;
  68. }
  69.  
  70. public RequestDispatcher getRequestDispatcher(String path) {
  71. return null;
  72. }
  73.  
  74. public boolean isSecure() {
  75. return false;
  76. }
  77.  
  78. public String getCharacterEncoding() {
  79. return null;
  80. }
  81.  
  82. public int getContentLength() {
  83. return 0;
  84. }
  85.  
  86. public String getContentType() {
  87. return null;
  88. }
  89.  
  90. public ServletInputStream getInputStream() throws IOException {
  91. return null;
  92. }
  93.  
  94. public Locale getLocale() {
  95. return null;
  96. }
  97.  
  98. public Enumeration getLocales() {
  99. return null;
  100. }
  101.  
  102. public String getParameter(String name) {
  103. return null;
  104. }
  105.  
  106. public Map getParameterMap() {
  107. return null;
  108. }
  109.  
  110. public Enumeration getParameterNames() {
  111. return null;
  112. }
  113.  
  114. public String[] getParameterValues(String parameter) {
  115. return null;
  116. }
  117.  
  118. public String getProtocol() {
  119. return null;
  120. }
  121.  
  122. public BufferedReader getReader() throws IOException {
  123. return null;
  124. }
  125.  
  126. public String getRemoteAddr() {
  127. return null;
  128. }
  129.  
  130. public String getRemoteHost() {
  131. return null;
  132. }
  133.  
  134. public String getScheme() {
  135. return null;
  136. }
  137.  
  138. public String getServerName() {
  139. return null;
  140. }
  141.  
  142. public int getServerPort() {
  143. return 0;
  144. }
  145.  
  146. public void removeAttribute(String attribute) {
  147. }
  148.  
  149. public void setAttribute(String key, Object value) {
  150. }
  151.  
  152. public void setCharacterEncoding(String encoding)
  153. throws UnsupportedEncodingException {
  154. }
  155.  
  156. }
  1. package ex02.pyrmont1;
  2.  
  3. import java.io.IOException;
  4. import java.io.BufferedReader;
  5. import java.io.UnsupportedEncodingException;
  6. import java.util.Enumeration;
  7. import java.util.Locale;
  8. import java.util.Map;
  9. import javax.servlet.RequestDispatcher;
  10. import javax.servlet.ServletInputStream;
  11. import javax.servlet.ServletRequest;
  12.  
  13. public class RequestFacade implements ServletRequest {
  14.  
  15. private ServletRequest request = null;
  16.  
  17. public RequestFacade(Request request) {
  18. this.request = request;
  19. }
  20.  
  21. /* implementation of the ServletRequest*/
  22. public Object getAttribute(String attribute) {
  23. return request.getAttribute(attribute);
  24. }
  25.  
  26. public Enumeration getAttributeNames() {
  27. return request.getAttributeNames();
  28. }
  29.  
  30. public String getRealPath(String path) {
  31. return request.getRealPath(path);
  32. }
  33.  
  34. public RequestDispatcher getRequestDispatcher(String path) {
  35. return request.getRequestDispatcher(path);
  36. }
  37.  
  38. public boolean isSecure() {
  39. return request.isSecure();
  40. }
  41.  
  42. public String getCharacterEncoding() {
  43. return request.getCharacterEncoding();
  44. }
  45.  
  46. public int getContentLength() {
  47. return request.getContentLength();
  48. }
  49.  
  50. public String getContentType() {
  51. return request.getContentType();
  52. }
  53.  
  54. public ServletInputStream getInputStream() throws IOException {
  55. return request.getInputStream();
  56. }
  57.  
  58. public Locale getLocale() {
  59. return request.getLocale();
  60. }
  61.  
  62. public Enumeration getLocales() {
  63. return request.getLocales();
  64. }
  65.  
  66. public String getParameter(String name) {
  67. return request.getParameter(name);
  68. }
  69.  
  70. public Map getParameterMap() {
  71. return request.getParameterMap();
  72. }
  73.  
  74. public Enumeration getParameterNames() {
  75. return request.getParameterNames();
  76. }
  77.  
  78. public String[] getParameterValues(String parameter) {
  79. return request.getParameterValues(parameter);
  80. }
  81.  
  82. public String getProtocol() {
  83. return request.getProtocol();
  84. }
  85.  
  86. public BufferedReader getReader() throws IOException {
  87. return request.getReader();
  88. }
  89.  
  90. public String getRemoteAddr() {
  91. return request.getRemoteAddr();
  92. }
  93.  
  94. public String getRemoteHost() {
  95. return request.getRemoteHost();
  96. }
  97.  
  98. public String getScheme() {
  99. return request.getScheme();
  100. }
  101.  
  102. public String getServerName() {
  103. return request.getServerName();
  104. }
  105.  
  106. public int getServerPort() {
  107. return request.getServerPort();
  108. }
  109.  
  110. public void removeAttribute(String attribute) {
  111. request.removeAttribute(attribute);
  112. }
  113.  
  114. public void setAttribute(String key, Object value) {
  115. request.setAttribute(key, value);
  116. }
  117.  
  118. public void setCharacterEncoding(String encoding)
  119. throws UnsupportedEncodingException {
  120. request.setCharacterEncoding(encoding);
  121. }
  122.  
  123. }
  1. package ex02.pyrmont1;
  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. "<h1>File Not Found</h1>";
  55. output.write(errorMessage.getBytes());
  56. }
  57. finally {
  58. if (fis!=null)
  59. fis.close();
  60. }
  61. }
  62.  
  63. /** implementation of ServletResponse */
  64. public void flushBuffer() throws IOException {
  65. }
  66.  
  67. public int getBufferSize() {
  68. return 0;
  69. }
  70.  
  71. public String getCharacterEncoding() {
  72. return null;
  73. }
  74.  
  75. public Locale getLocale() {
  76. return null;
  77. }
  78.  
  79. public ServletOutputStream getOutputStream() throws IOException {
  80. return null;
  81. }
  82.  
  83. public PrintWriter getWriter() throws IOException {
  84. // autoflush is true, println() will flush,
  85. // but print() will not.
  86. writer = new PrintWriter(output, true);
  87. return writer;
  88. }
  89.  
  90. public boolean isCommitted() {
  91. return false;
  92. }
  93.  
  94. public void reset() {
  95. }
  96.  
  97. public void resetBuffer() {
  98. }
  99.  
  100. public void setBufferSize(int size) {
  101. }
  102.  
  103. public void setContentLength(int length) {
  104. }
  105.  
  106. public void setContentType(String type) {
  107. }
  108.  
  109. public void setLocale(Locale locale) {
  110. }
  111. }
  1. package ex02.pyrmont1;
  2.  
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import java.util.Locale;
  6. import javax.servlet.ServletResponse;
  7. import javax.servlet.ServletOutputStream;
  8.  
  9. public class ResponseFacade implements ServletResponse {
  10.  
  11. private ServletResponse response;
  12. public ResponseFacade(Response response) {
  13. this.response = response;
  14. }
  15.  
  16. public void flushBuffer() throws IOException {
  17. response.flushBuffer();
  18. }
  19.  
  20. public int getBufferSize() {
  21. return response.getBufferSize();
  22. }
  23.  
  24. public String getCharacterEncoding() {
  25. return response.getCharacterEncoding();
  26. }
  27.  
  28. public Locale getLocale() {
  29. return response.getLocale();
  30. }
  31.  
  32. public ServletOutputStream getOutputStream() throws IOException {
  33. return response.getOutputStream();
  34. }
  35.  
  36. public PrintWriter getWriter() throws IOException {
  37. return response.getWriter();
  38. }
  39.  
  40. public boolean isCommitted() {
  41. return response.isCommitted();
  42. }
  43.  
  44. public void reset() {
  45. response.reset();
  46. }
  47.  
  48. public void resetBuffer() {
  49. response.resetBuffer();
  50. }
  51.  
  52. public void setBufferSize(int size) {
  53. response.setBufferSize(size);
  54. }
  55.  
  56. public void setContentLength(int length) {
  57. response.setContentLength(length);
  58. }
  59.  
  60. public void setContentType(String type) {
  61. response.setContentType(type);
  62. }
  63.  
  64. public void setLocale(Locale locale) {
  65. response.setLocale(locale);
  66. }
  67.  
  68. }
  1. package ex02.pyrmont1;
  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 ServletProcessor2 {
  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. URL[] urls = new URL[1];
  22. URLStreamHandler streamHandler = null;
  23. File classPath = new File(Constants.WEB_ROOT);
  24. String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString() ;
  25. urls[0] = new URL(null, repository, streamHandler);
  26. loader = new URLClassLoader(urls);
  27. }
  28. catch (IOException e) {
  29. System.out.println(e.toString() );
  30. }
  31. Class myClass = null;
  32. try {
  33. myClass = loader.loadClass(servletName);
  34. }
  35. catch (ClassNotFoundException e) {
  36. System.out.println(e.toString());
  37. }
  38.  
  39. Servlet servlet = null;
  40. RequestFacade requestFacade = new RequestFacade(request);
  41. ResponseFacade responseFacade = new ResponseFacade(response);
  42. try {
  43. servlet = (Servlet) myClass.newInstance();
  44. servlet.service((ServletRequest) requestFacade, (ServletResponse) responseFacade);
  45. }
  46. catch (Exception e) {
  47. System.out.println(e.toString());
  48. }
  49. catch (Throwable e) {
  50. System.out.println(e.toString());
  51. }
  52.  
  53. }
  54. }
  1. package ex02.pyrmont1;
  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. }

tomcat2章2的更多相关文章

  1. tomcat2章1

    package ex02.pyrmont; import java.io.File; public class Constants { public static final String WEB_R ...

  2. 《Django By Example》第五章 中文 翻译 (个人学习,渣翻)

    书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者@ucag注:大家好,我是新来的翻译, ...

  3. ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第二章:利用模型类创建视图、控制器和数据库

    在这一章中,我们将直接进入项目,并且为产品和分类添加一些基本的模型类.我们将在Entity Framework的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...

  4. 《Django By Example》第四章 中文 翻译 (个人学习,渣翻)

    书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者注:祝大家新年快乐,这次带来<D ...

  5. 《Django By Example》第三章 中文 翻译 (个人学习,渣翻)

    书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者注:第三章滚烫出炉,大家请不要吐槽文中 ...

  6. 《Django By Example》第二章 中文 翻译 (个人学习,渣翻)

    书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者注:翻译完第一章后,发现翻译第二章的速 ...

  7. 《Django By Example》第一章 中文 翻译 (个人学习,渣翻)

    书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者注:本人目前在杭州某家互联网公司工作, ...

  8. ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第一章:创建基本的MVC Web站点

    在这一章中,我们将学习如何使用基架快速搭建和运行一个简单的Microsoft ASP.NET MVC Web站点.在我们马上投入学习和编码之前,我们首先了解一些有关ASP.NET MVC和Entity ...

  9. ASP.NET Core 中文文档 第四章 MVC(4.2)控制器操作的路由

    原文:Routing to Controller Actions 作者:Ryan Nowak.Rick Anderson 翻译:娄宇(Lyrics) 校对:何镇汐.姚阿勇(Dr.Yao) ASP.NE ...

随机推荐

  1. iOS添加pch文件

    1.第一步,创建pch文件 第二步设置pch文件:相对地址,填写$(SRCROOT)/YTCompleteCarSell/PrefixHeader.pch  $(SRCROOT)是项目地址/项目名/p ...

  2. android打印日志封装

    public class LogUtils { static String className;//类名 static String methodName;//方法名 static int lineN ...

  3. 003-RFC关于媒体类型说明

    一.概述 RFC-822   Standard for ARPA Internet text messages [ARPA互连网文本信息标准]RFC-2045 MIME Part 1: Format ...

  4. pycharm的小问题之光标

    一大早起来,突然发现pycharm的光变粗,按退格键会删除编写的内容,超级难受(如下图), 百度一下,也不知道在百度框里输什么关键字好,但最后还是找到了,哈哈.... ​ 解决方法: 1.按键盘上In ...

  5. python基础入门--input标签、变量、数字类型、列表、字符串、字典、索引值、bool值、占位符格式输出

    # 在python3 中: # nian=input('>>:') #请输入什么类型的值,都成字符串类型# print(type(nian)) # a = 2**64# print(typ ...

  6. Mongodb 基础 查询表达式

    数据库操作 查看:show dbs; 创建:use dbname; // db.createCollection('collection_name');    隐式创建,需要创建的数据库中有表才表示创 ...

  7. IOC解耦-面向接口编程的优点

    原文:https://blog.csdn.net/jj_nan/article/details/70161086 参考:https://www.cnblogs.com/landeanfen/p/477 ...

  8. [LeetCode] 610. Triangle Judgement_Easy tag: SQL

    A pupil Tim gets homework to identify whether three line segments could possibly form a triangle. Ho ...

  9. 分享一个.NET(C#)按指定字母个数截断英文字符串的方法–提供枚举选项,可保留完整单词

    分享一个.NET(C#)按字母个数截断英文字符串的方法,该方法提供枚举选项.枚举选项包括:可保留完整单词,允许最后一个单词超过最大长度限制,字符串最后跟省略号以及不采取任何操作等,具体示例实现代码如下 ...

  10. HTop依赖包

    htop 是一个 Linux 下的交互式的进程浏览器,可以用来替换Linux下的top命令. 1.安装HTop时需要先安装依赖包:rpmforge-release-0.5.3-1.el6.rf.x86 ...