tomcat2章1
package ex02.pyrmont; import java.io.File; public class Constants {
public static final String WEB_ROOT =
System.getProperty("user.dir") + File.separator + "webroot";
}
package ex02.pyrmont; 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 HttpServer1 { private static final String SHUTDOWN_COMMAND = "/SHUTDOWN"; private boolean shutdown = false; public static void main(String[] args) {
HttpServer1 server = new HttpServer1();
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);
} 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); // a request for a servlet begins with "/servlet/"
if (request.getUri().startsWith("/servlet/")) {
ServletProcessor1 processor = new ServletProcessor1();
processor.process(request, response); //根据url后面的参数 找到servlet去处理
}
else {//处理页面等资源
StaticResourceProcessor processor = new StaticResourceProcessor();
processor.process(request, response);
} socket.close();
shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
}
package ex02.pyrmont; 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() {
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.pyrmont; 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;
} 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.pyrmont; 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 ServletProcessor1 { 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; try {
servlet = (Servlet) myClass.newInstance();
servlet.service((ServletRequest) request, (ServletResponse) response);
}
catch (Exception e) {
System.out.println(e.toString());
}
catch (Throwable e) {
System.out.println(e.toString());
} }
}
package ex02.pyrmont; import java.io.IOException; public class StaticResourceProcessor { public void process(Request request, Response response) {
try {
response.sendStaticResource();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
tomcat2章1的更多相关文章
- tomcat2章2
package ex02.pyrmont1; import java.io.File; public class Constants { public static final String WEB_ ...
- 《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 ...
随机推荐
- MySQL最优配置模板( 5.6&5.7转)
[client] user = root --用户 password = 1111aaA_ -- 密码 [mysql] prompt = [\\u@\\p][\\d]>\\_ -- cmd控制台 ...
- 安全易用的云许可-VirboxLM许可管理平台
Virbox LM是深思推出的基于云许可管理的开放平台,旨在为开发者提供低成本.高强度.操作便捷的一站式软件保护方案. Virbox LM包括用户许可管理工具.加壳工具.API帮助工具.开发商管理工具 ...
- openssl生成RSA公钥和私钥对
在ubuntu上要使用openssl的话需要先进行安装,命令如下: sudo apt-get install openssl 安装完成就可以使用openssl了. 首先需要进入openssl的交互界面 ...
- vbox中安装mac系统
参考: https://www.cnblogs.com/liming2017/p/7566953.html
- VirtualBox修改现有VDI虚拟磁盘大小
之前创建的虚拟磁盘10G,现需要更大的空间,而又不想使用新增虚拟磁盘的方法. 通过查看资料发现VirtulBox提供的VBoxManage modifyhd命令可以解决,该命令的具体用法: VBoxM ...
- iOSOpenDev安装使用
下载:http://iosopendev.com/download/ 选择“iOSOpenDev 1.6-2 Installer” 出错解决方法 https://www.jianshu.com/p/2 ...
- eclipse的调试模式以及断点运行
先在代码序号处打个点. 点击debug调试模式 然后再点击 如果有打断点,则会在断点处结束,如果没有,会一直一步一步向下直至结束.
- 编写一个程序解决选择问题。令k=N/2。
import java.util.Arrays; /** * 选择问题,确定N个数中第K个最大值 * @author wulei * 将前k个数读进一个数组,冒泡排序(递减),再将剩下的元素逐个读入, ...
- C++ 使用openssl库实现 DES 加密——CBC模式 && RSA加密——公加私解——私加公解
之前工作上需要用C++把软件生成的用户序列号用des加密cbc的模式,加密后为二进制,转化为十六进制,然后提供给java写的授权码管理平台. java平台会根据用户序列号,生成一个授权码,授权码是用r ...
- vue--监听属性完成大小写字母间的转换
监听属性 watch侦听属性的作用是侦听某属性值的变化,从而做相应的操作,侦听属性是一个对象,它的键是要监听的对象或者变量,值一般是函数,当你侦听的元素发生变化时,需要执行的函数,这个函数有两个形参, ...