Tomcat 是一个的 Web Server,它也是一个满足 Servlet 规范的容器。我们想要在浏览器上运行自己的项目,那么就必须把web项目放到服务器中运行,而tomcat正是一个很好的webserver。
Java实现tomcat的功能的思路:tomcat的启动是基于socket服务,它支持 HTTP 协议!,将请求和响应封装成request和response。利用反射实例化具体的 Servlet 中,用io流将内容输出到浏览器。
项目目录
封装请求类:Myrequest.java
package com.tomcat;
import java.io.IOException;
import java.io.InputStream;
/**
* 封装请求对象
*通过输入流,对 HTTP 协议进行解析,
*拿到了 HTTP 请求头的方法以及 URL。
* @author黄钟亮hzl
*2018年12月15日
*/
public class MyRequest {
private String url;
private String method;
public MyRequest(InputStream inputStream) throws IOException {
String httpRequest = "";
byte[] httpRequestBytes = new byte[1024];
int length = 0;
if ((length = inputStream.read(httpRequestBytes))>0){
httpRequest = new String(httpRequestBytes , 0 ,length);
}
//http 请求协议
//System.out.println(httpRequest);
//通过字符串截取URL和请求方法
String httpHead = httpRequest.split("\n")[0];
method = httpHead.split("\\s")[0];
url = httpHead.split("\\s")[1];
System.out.println(this);
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public String toString() {
return "MyRequest [url=" + url + ", method=" + method + "]";
}
}
封装响应类:Myresponse.java
package com.tomcat;
import java.io.IOException;
import java.io.OutputStream;
/**
* 封装响应对象
* 基于HTTP协议的格式进行输出写入
* @author黄钟亮hzl
*2018年12月15日
*/
public class MyResponse {