tomcat2章2
- package ex02.pyrmont1;
- import java.io.File;
- public class Constants {
- public static final String WEB_ROOT =
- System.getProperty("user.dir") + File.separator + "webroot";
- }
- package ex02.pyrmont1;
- import java.net.Socket;
- import java.net.ServerSocket;
- import java.net.InetAddress;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.io.IOException;
- public class HttpServer2 {
- // shutdown command
- private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
- // the shutdown command received
- private boolean shutdown = false;
- public static void main(String[] args) {
- HttpServer2 server = new HttpServer2();
- 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);
- }
- // Loop waiting for a request
- while (!shutdown) {
- Socket socket = null;
- InputStream input = null;
- OutputStream output = null;
- try {
- socket = serverSocket.accept();
- input = socket.getInputStream();
- output = socket.getOutputStream();
- // create Request object and parse
- Request request = new Request(input);
- request.parse();
- // create Response object
- Response response = new Response(output);
- response.setRequest(request);
- //check if this is a request for a servlet or a static resource
- //a request for a servlet begins with "/servlet/"
- if (request.getUri().startsWith("/servlet/")) {
- ServletProcessor2 processor = new ServletProcessor2();
- processor.process(request, response);
- }
- else {
- StaticResourceProcessor processor = new StaticResourceProcessor();
- processor.process(request, response);
- }
- // Close the socket
- socket.close();
- //check if the previous URI is a shutdown command
- shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
- }
- catch (Exception e) {
- e.printStackTrace();
- System.exit(1);
- }
- }
- }
- }
- package ex02.pyrmont1;
- import java.io.InputStream;
- import java.io.IOException;
- import java.io.BufferedReader;
- import java.io.UnsupportedEncodingException;
- import java.util.Enumeration;
- import java.util.Locale;
- import java.util.Map;
- import javax.servlet.RequestDispatcher;
- import javax.servlet.ServletInputStream;
- import javax.servlet.ServletRequest;
- public class Request implements ServletRequest {
- private InputStream input;
- private String uri;
- public Request(InputStream input) {
- this.input = input;
- }
- public String getUri() {
- return uri;
- }
- 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 void parse() {
- // Read a set of characters from the socket
- 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());
- }
- /* implementation of the ServletRequest*/
- public Object getAttribute(String attribute) {
- return null;
- }
- public Enumeration getAttributeNames() {
- return null;
- }
- public String getRealPath(String path) {
- return null;
- }
- public RequestDispatcher getRequestDispatcher(String path) {
- return null;
- }
- public boolean isSecure() {
- return false;
- }
- public String getCharacterEncoding() {
- return null;
- }
- public int getContentLength() {
- return 0;
- }
- public String getContentType() {
- return null;
- }
- public ServletInputStream getInputStream() throws IOException {
- return null;
- }
- public Locale getLocale() {
- return null;
- }
- public Enumeration getLocales() {
- return null;
- }
- public String getParameter(String name) {
- return null;
- }
- public Map getParameterMap() {
- return null;
- }
- public Enumeration getParameterNames() {
- return null;
- }
- public String[] getParameterValues(String parameter) {
- return null;
- }
- public String getProtocol() {
- return null;
- }
- public BufferedReader getReader() throws IOException {
- return null;
- }
- public String getRemoteAddr() {
- return null;
- }
- public String getRemoteHost() {
- return null;
- }
- public String getScheme() {
- return null;
- }
- public String getServerName() {
- return null;
- }
- public int getServerPort() {
- return 0;
- }
- public void removeAttribute(String attribute) {
- }
- public void setAttribute(String key, Object value) {
- }
- public void setCharacterEncoding(String encoding)
- throws UnsupportedEncodingException {
- }
- }
- package ex02.pyrmont1;
- import java.io.IOException;
- import java.io.BufferedReader;
- import java.io.UnsupportedEncodingException;
- import java.util.Enumeration;
- import java.util.Locale;
- import java.util.Map;
- import javax.servlet.RequestDispatcher;
- import javax.servlet.ServletInputStream;
- import javax.servlet.ServletRequest;
- public class RequestFacade implements ServletRequest {
- private ServletRequest request = null;
- public RequestFacade(Request request) {
- this.request = request;
- }
- /* implementation of the ServletRequest*/
- public Object getAttribute(String attribute) {
- return request.getAttribute(attribute);
- }
- public Enumeration getAttributeNames() {
- return request.getAttributeNames();
- }
- public String getRealPath(String path) {
- return request.getRealPath(path);
- }
- public RequestDispatcher getRequestDispatcher(String path) {
- return request.getRequestDispatcher(path);
- }
- public boolean isSecure() {
- return request.isSecure();
- }
- public String getCharacterEncoding() {
- return request.getCharacterEncoding();
- }
- public int getContentLength() {
- return request.getContentLength();
- }
- public String getContentType() {
- return request.getContentType();
- }
- public ServletInputStream getInputStream() throws IOException {
- return request.getInputStream();
- }
- public Locale getLocale() {
- return request.getLocale();
- }
- public Enumeration getLocales() {
- return request.getLocales();
- }
- public String getParameter(String name) {
- return request.getParameter(name);
- }
- public Map getParameterMap() {
- return request.getParameterMap();
- }
- public Enumeration getParameterNames() {
- return request.getParameterNames();
- }
- public String[] getParameterValues(String parameter) {
- return request.getParameterValues(parameter);
- }
- public String getProtocol() {
- return request.getProtocol();
- }
- public BufferedReader getReader() throws IOException {
- return request.getReader();
- }
- public String getRemoteAddr() {
- return request.getRemoteAddr();
- }
- public String getRemoteHost() {
- return request.getRemoteHost();
- }
- public String getScheme() {
- return request.getScheme();
- }
- public String getServerName() {
- return request.getServerName();
- }
- public int getServerPort() {
- return request.getServerPort();
- }
- public void removeAttribute(String attribute) {
- request.removeAttribute(attribute);
- }
- public void setAttribute(String key, Object value) {
- request.setAttribute(key, value);
- }
- public void setCharacterEncoding(String encoding)
- throws UnsupportedEncodingException {
- request.setCharacterEncoding(encoding);
- }
- }
- package ex02.pyrmont1;
- import java.io.OutputStream;
- import java.io.IOException;
- import java.io.FileInputStream;
- import java.io.FileNotFoundException;
- import java.io.File;
- import java.io.PrintWriter;
- import java.util.Locale;
- import javax.servlet.ServletResponse;
- import javax.servlet.ServletOutputStream;
- public class Response implements ServletResponse {
- private static final int BUFFER_SIZE = 1024;
- Request request;
- OutputStream output;
- PrintWriter writer;
- public Response(OutputStream output) {
- this.output = output;
- }
- public void setRequest(Request request) {
- this.request = request;
- }
- /* This method is used to serve a static page */
- public void sendStaticResource() throws IOException {
- byte[] bytes = new byte[BUFFER_SIZE];
- FileInputStream fis = null;
- try {
- /* request.getUri has been replaced by request.getRequestURI */
- File file = new File(Constants.WEB_ROOT, request.getUri());
- fis = new FileInputStream(file);
- /*
- HTTP Response = Status-Line
- *(( general-header | response-header | entity-header ) CRLF)
- CRLF
- [ message-body ]
- Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
- */
- int ch = fis.read(bytes, 0, BUFFER_SIZE);
- while (ch!=-1) {
- output.write(bytes, 0, ch);
- ch = fis.read(bytes, 0, BUFFER_SIZE);
- }
- }
- catch (FileNotFoundException e) {
- 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());
- }
- finally {
- if (fis!=null)
- fis.close();
- }
- }
- /** implementation of ServletResponse */
- public void flushBuffer() throws IOException {
- }
- public int getBufferSize() {
- return 0;
- }
- public String getCharacterEncoding() {
- return null;
- }
- public Locale getLocale() {
- 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;
- }
- public boolean isCommitted() {
- return false;
- }
- public void reset() {
- }
- public void resetBuffer() {
- }
- public void setBufferSize(int size) {
- }
- public void setContentLength(int length) {
- }
- public void setContentType(String type) {
- }
- public void setLocale(Locale locale) {
- }
- }
- package ex02.pyrmont1;
- import java.io.IOException;
- import java.io.PrintWriter;
- import java.util.Locale;
- import javax.servlet.ServletResponse;
- import javax.servlet.ServletOutputStream;
- public class ResponseFacade implements ServletResponse {
- private ServletResponse response;
- public ResponseFacade(Response response) {
- this.response = response;
- }
- public void flushBuffer() throws IOException {
- response.flushBuffer();
- }
- public int getBufferSize() {
- return response.getBufferSize();
- }
- public String getCharacterEncoding() {
- return response.getCharacterEncoding();
- }
- public Locale getLocale() {
- return response.getLocale();
- }
- public ServletOutputStream getOutputStream() throws IOException {
- return response.getOutputStream();
- }
- public PrintWriter getWriter() throws IOException {
- return response.getWriter();
- }
- public boolean isCommitted() {
- return response.isCommitted();
- }
- public void reset() {
- response.reset();
- }
- public void resetBuffer() {
- response.resetBuffer();
- }
- public void setBufferSize(int size) {
- response.setBufferSize(size);
- }
- public void setContentLength(int length) {
- response.setContentLength(length);
- }
- public void setContentType(String type) {
- response.setContentType(type);
- }
- public void setLocale(Locale locale) {
- response.setLocale(locale);
- }
- }
- package ex02.pyrmont1;
- import java.net.URL;
- import java.net.URLClassLoader;
- import java.net.URLStreamHandler;
- import java.io.File;
- import java.io.IOException;
- import javax.servlet.Servlet;
- import javax.servlet.ServletRequest;
- import javax.servlet.ServletResponse;
- public class ServletProcessor2 {
- 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) {
- System.out.println(e.toString() );
- }
- Class myClass = null;
- try {
- myClass = loader.loadClass(servletName);
- }
- catch (ClassNotFoundException e) {
- System.out.println(e.toString());
- }
- Servlet servlet = null;
- RequestFacade requestFacade = new RequestFacade(request);
- ResponseFacade responseFacade = new ResponseFacade(response);
- try {
- servlet = (Servlet) myClass.newInstance();
- servlet.service((ServletRequest) requestFacade, (ServletResponse) responseFacade);
- }
- catch (Exception e) {
- System.out.println(e.toString());
- }
- catch (Throwable e) {
- System.out.println(e.toString());
- }
- }
- }
- package ex02.pyrmont1;
- import java.io.IOException;
- public class StaticResourceProcessor {
- public void process(Request request, Response response) {
- try {
- response.sendStaticResource();
- }
- catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
tomcat2章2的更多相关文章
- tomcat2章1
package ex02.pyrmont; import java.io.File; public class Constants { public static final String WEB_R ...
- 《Django By Example》第五章 中文 翻译 (个人学习,渣翻)
书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者@ucag注:大家好,我是新来的翻译, ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第二章:利用模型类创建视图、控制器和数据库
在这一章中,我们将直接进入项目,并且为产品和分类添加一些基本的模型类.我们将在Entity Framework的代码优先模式下,利用这些模型类创建一个数据库.我们还将学习如何在代码中创建数据库上下文类 ...
- 《Django By Example》第四章 中文 翻译 (个人学习,渣翻)
书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者注:祝大家新年快乐,这次带来<D ...
- 《Django By Example》第三章 中文 翻译 (个人学习,渣翻)
书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者注:第三章滚烫出炉,大家请不要吐槽文中 ...
- 《Django By Example》第二章 中文 翻译 (个人学习,渣翻)
书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者注:翻译完第一章后,发现翻译第二章的速 ...
- 《Django By Example》第一章 中文 翻译 (个人学习,渣翻)
书籍出处:https://www.packtpub.com/web-development/django-example 原作者:Antonio Melé (译者注:本人目前在杭州某家互联网公司工作, ...
- ASP.NET MVC with Entity Framework and CSS一书翻译系列文章之第一章:创建基本的MVC Web站点
在这一章中,我们将学习如何使用基架快速搭建和运行一个简单的Microsoft ASP.NET MVC Web站点.在我们马上投入学习和编码之前,我们首先了解一些有关ASP.NET MVC和Entity ...
- ASP.NET Core 中文文档 第四章 MVC(4.2)控制器操作的路由
原文:Routing to Controller Actions 作者:Ryan Nowak.Rick Anderson 翻译:娄宇(Lyrics) 校对:何镇汐.姚阿勇(Dr.Yao) ASP.NE ...
随机推荐
- iOS添加pch文件
1.第一步,创建pch文件 第二步设置pch文件:相对地址,填写$(SRCROOT)/YTCompleteCarSell/PrefixHeader.pch $(SRCROOT)是项目地址/项目名/p ...
- android打印日志封装
public class LogUtils { static String className;//类名 static String methodName;//方法名 static int lineN ...
- 003-RFC关于媒体类型说明
一.概述 RFC-822 Standard for ARPA Internet text messages [ARPA互连网文本信息标准]RFC-2045 MIME Part 1: Format ...
- pycharm的小问题之光标
一大早起来,突然发现pycharm的光变粗,按退格键会删除编写的内容,超级难受(如下图), 百度一下,也不知道在百度框里输什么关键字好,但最后还是找到了,哈哈.... 解决方法: 1.按键盘上In ...
- python基础入门--input标签、变量、数字类型、列表、字符串、字典、索引值、bool值、占位符格式输出
# 在python3 中: # nian=input('>>:') #请输入什么类型的值,都成字符串类型# print(type(nian)) # a = 2**64# print(typ ...
- Mongodb 基础 查询表达式
数据库操作 查看:show dbs; 创建:use dbname; // db.createCollection('collection_name'); 隐式创建,需要创建的数据库中有表才表示创 ...
- IOC解耦-面向接口编程的优点
原文:https://blog.csdn.net/jj_nan/article/details/70161086 参考:https://www.cnblogs.com/landeanfen/p/477 ...
- [LeetCode] 610. Triangle Judgement_Easy tag: SQL
A pupil Tim gets homework to identify whether three line segments could possibly form a triangle. Ho ...
- 分享一个.NET(C#)按指定字母个数截断英文字符串的方法–提供枚举选项,可保留完整单词
分享一个.NET(C#)按字母个数截断英文字符串的方法,该方法提供枚举选项.枚举选项包括:可保留完整单词,允许最后一个单词超过最大长度限制,字符串最后跟省略号以及不采取任何操作等,具体示例实现代码如下 ...
- HTop依赖包
htop 是一个 Linux 下的交互式的进程浏览器,可以用来替换Linux下的top命令. 1.安装HTop时需要先安装依赖包:rpmforge-release-0.5.3-1.el6.rf.x86 ...