tomcat底层原理实现

时间:2021-09-01 16:40:19

1、首先完成一个server类,用来接收客户端的请求;代码都在一个while(true)循环中,模拟tomcat一直在启动,其中绑定一个端口,用来监听一个端口,然后创建一个输入流,获取请求的输入流,然后将输入流中的uri和参数通过request获取出来,然后通过response答应出来。

 package com.dongnao.mytomcat;

 import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.Date; public class Server {
private static int count=0;
public static void main(String[] args) {
ServerSocket ss=null;
Socket socket=null;
SimpleDateFormat format=new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
String time=format.format(new Date()); try {
ss=new ServerSocket(9994);
System.out.println("已经连接服务器"); while(true){
socket =ss.accept();
count++;
System.out.println("第几次连接:"+count); InputStream is=socket.getInputStream();
Request request=new Request(is); OutputStream os=socket.getOutputStream(); Response response= new Response(os); //业务逻辑 ,获取静态资源;
String uri=request.getUri();
System.out.println(uri);
//判定这个是不是静态资源
if(isStaticSourse(uri)){
response.writeFile(uri.substring(1));
}else if(uri.endsWith(".action")){
if(uri.endsWith("/login.action")){
//取账户和密码
LoginServlet servlet=new LoginServlet();
try {
servlet.service(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}
}
//出while循环后要关闭
os.close();
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
} }
public static boolean isStaticSourse(String uri){
String[] suffixString={"html","css","js","jpg","jepg","png"};
boolean isStatic =false;
for(String suffix:suffixString){
if(uri.endsWith("."+suffix)){
isStatic=true;
break;
}
} return isStatic;
} }

2、创建一个request类,用来模拟request对象,用来获取对应的uri和参数,其中请求方式有get和post,get的也有参数,这里没忽略了,主要涉及的是post的请求方式,然后截取post中的请求参数。

 package com.dongnao.mytomcat;

 import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
/**
* 解析请求类,解析请求资源的地址
* @author CYA
*
*/
public class Request {
private String uri;
private String pString;
//halderMap
private HashMap<String,String> paramMap=new HashMap<String,String>();
//取得客户参数名称;
public String getParamName(String key){ return paramMap.get(key);
}
public Request(InputStream is) throws IOException{
byte[] buff=new byte[1024];
int len=is.read(buff);
if(len>0){
String msg=new String(buff,0,len);
int start=msg.indexOf("GET")+4;
if(msg.indexOf("POST")!=-1){
start=msg.indexOf("POST")+5;
}
int end=msg.indexOf("HTTP/1.1")-1;
//获取对应的uri路径
uri=msg.substring(start, end);
if(msg.startsWith("POST")){
int paramString=msg.lastIndexOf("\n");
pString=msg.substring(paramString+1);
String [] parms=pString.split("&");
for(String parm:parms){
String[] temp= parm.split("=");
paramMap.put(temp[0], temp[1]);
}
}
System.out.println("-----"+uri+"-----"); }else{
System.out.println("bad request");
}
}
public String getUri() {
return uri;
}
public void setUri(String uri) {
this.uri = uri;
} }

3、创建一个response类,用来模拟response对象,其中主要是通过读取对应的静态资源,然后

 package com.dongnao.mytomcat;

 import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream; /**
*��Ӧ�ķ�װ�ࣺд��Ϣ��ͻ���
* @author CYA
*
*/
public class Response {
private OutputStream os=null;
public Response(OutputStream os) {
this.os=os;
}
public void writeContent(String content) throws IOException{
content="HTTP/1.0 200 OK\nContent-type:text/html; charset=utf-8\n\n"+content;
os.write(content.getBytes());
os.flush();
os.close();
}
/**
* ��̬��Ӧ�������
* @param path
* @throws IOException
*/
public void writeHtmlFile(String path) throws IOException{
String htmlContentString=FileUtils.getFileContent(path);
writeContent(htmlContentString);
}
public void writeFile(String path){
//读取文件
try {
FileInputStream fis=new FileInputStream(path);
byte[] buff=new byte[512];
int len=0;
while((len=fis.read(buff))!=-1){
os.write(buff, 0, len);
}
fis.close();
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
}

4、创建一个loginservlet用来模拟dispacherservlet,封装request和response对象

 package com.dongnao.mytomcat;

 public class LoginServlet {
public void service(Request request,Response response) throws Exception{
String username=request.getParamName("username");
String password=request.getParamName("pwd");
if(username!=null&&username.equals("admin")&&password!=null&&password.equals("123")){
response.writeHtmlFile("welcome.html");
}else{
response.writeHtmlFile("error.html");
}
}
}

5其中封装了一个工具类,用来封装读取文件的内容。

 package com.dongnao.mytomcat;

 import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException; /**
*读取文件的工具类
* @author CYA
*
*/
public class FileUtils {
/**
* 工具类
*/
public static String getFileContent(String path){
StringBuffer sb=new StringBuffer();
FileReader fr=null;
BufferedReader br=null;
try {
fr=new FileReader(path);
br=new BufferedReader(fr);
String line=null;
while((line=br.readLine())!=null){
sb.append(line);
}
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}