zoukankan      html  css  js  c++  java
  • tomcat底层原理实现

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

     1 package com.dongnao.mytomcat;
     2 
     3 import java.io.IOException;
     4 import java.io.InputStream;
     5 import java.io.OutputStream;
     6 import java.net.ServerSocket;
     7 import java.net.Socket;
     8 import java.text.SimpleDateFormat;
     9 import java.util.Date;
    10 
    11 public class Server {
    12     private static int count=0;
    13     public static void main(String[] args) {
    14         ServerSocket ss=null;
    15         Socket socket=null;
    16         SimpleDateFormat  format=new SimpleDateFormat("yyy-MM-dd HH:mm:ss"); 
    17         String time=format.format(new Date());
    18     
    19         try {
    20             ss=new ServerSocket(9994);
    21             System.out.println("已经连接服务器");
    22         
    23             while(true){
    24                 socket =ss.accept();
    25                 count++;
    26                 System.out.println("第几次连接:"+count);
    27                 
    28                 InputStream is=socket.getInputStream();
    29                 Request request=new Request(is);
    30                 
    31                 OutputStream os=socket.getOutputStream();
    32                 
    33                 Response response= new Response(os);
    34                 
    35                 
    36                 
    37                 //业务逻辑 ,获取静态资源;
    38                 String uri=request.getUri();
    39                 System.out.println(uri);
    40                 //判定这个是不是静态资源
    41                 if(isStaticSourse(uri)){
    42                     response.writeFile(uri.substring(1));
    43                 }else if(uri.endsWith(".action")){
    44                     if(uri.endsWith("/login.action")){
    45                         //取账户和密码
    46                         LoginServlet servlet=new LoginServlet();
    47                         try {
    48                             servlet.service(request, response);
    49                         } catch (Exception e) {
    50                             e.printStackTrace();
    51                         }
    52                     }
    53                 }    
    54                 //出while循环后要关闭
    55                 os.close();
    56                 socket.close();
    57             }
    58         } catch (IOException e) {
    59             e.printStackTrace();
    60         }
    61         
    62     }
    63     public static boolean isStaticSourse(String uri){
    64         String[] suffixString={"html","css","js","jpg","jepg","png"};
    65         boolean isStatic =false;
    66         for(String suffix:suffixString){
    67             if(uri.endsWith("."+suffix)){
    68                 isStatic=true;
    69                 break;
    70             }
    71         }
    72         
    73         return isStatic;
    74     }
    75 
    76 }
    View Code

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

     1 package com.dongnao.mytomcat;
     2 
     3 import java.io.IOException;
     4 import java.io.InputStream;
     5 import java.util.HashMap;
     6 /**
     7  * 解析请求类,解析请求资源的地址
     8  * @author CYA
     9  *
    10  */
    11 public class Request {
    12     private String uri;
    13     private String pString;
    14     //halderMap
    15     private HashMap<String,String> paramMap=new HashMap<String,String>();
    16     //取得客户参数名称;
    17     public String getParamName(String key){
    18         
    19         return paramMap.get(key);
    20     }
    21     public Request(InputStream is) throws IOException{
    22          byte[] buff=new byte[1024];
    23          int len=is.read(buff);
    24         if(len>0){ 
    25              String msg=new String(buff,0,len);
    26              int start=msg.indexOf("GET")+4;
    27              if(msg.indexOf("POST")!=-1){
    28                  start=msg.indexOf("POST")+5;
    29              }
    30              int end=msg.indexOf("HTTP/1.1")-1;
    31              //获取对应的uri路径
    32              uri=msg.substring(start, end);
    33              if(msg.startsWith("POST")){
    34                  int paramString=msg.lastIndexOf("
    ");
    35                  pString=msg.substring(paramString+1);
    36                  String [] parms=pString.split("&");
    37                  for(String parm:parms){
    38                      String[] temp= parm.split("=");
    39                      paramMap.put(temp[0], temp[1]);
    40                  }
    41              }
    42              System.out.println("-----"+uri+"-----");
    43              
    44              
    45          }else{
    46              System.out.println("bad request");
    47          }
    48     }
    49     public String getUri() {
    50         return uri;
    51     }
    52     public void setUri(String uri) {
    53         this.uri = uri;
    54     }
    55     
    56 }
    View Code

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

     1 package com.dongnao.mytomcat;
     2 
     3 import java.io.FileInputStream;
     4 import java.io.FileNotFoundException;
     5 import java.io.IOException;
     6 import java.io.OutputStream;
     7 
     8 /**
     9  *��Ӧ�ķ�װ�ࣺд��Ϣ��ͻ���
    10  * @author CYA
    11  *
    12  */
    13 public class Response {
    14     private OutputStream os=null;
    15     public Response(OutputStream os) {
    16         this.os=os;
    17     }
    18     public void writeContent(String content) throws IOException{
    19         content="HTTP/1.0 200 OK
    Content-type:text/html; charset=utf-8
    
    "+content;
    20         os.write(content.getBytes());
    21         os.flush();
    22         os.close();
    23     }
    24     /**
    25      * ��̬��Ӧ�������
    26      * @param path
    27      * @throws IOException
    28      */
    29     public void writeHtmlFile(String path) throws IOException{
    30         String htmlContentString=FileUtils.getFileContent(path);
    31         writeContent(htmlContentString);
    32     }
    33     public void writeFile(String path){
    34         //读取文件
    35         try {
    36             FileInputStream fis=new FileInputStream(path);
    37             byte[] buff=new byte[512];
    38             int len=0;
    39             while((len=fis.read(buff))!=-1){
    40                 os.write(buff, 0, len);
    41             }
    42             fis.close();
    43             os.flush();
    44             os.close();
    45         } catch (FileNotFoundException e) {
    46             e.printStackTrace();
    47         } catch (IOException e) {
    48             e.printStackTrace();
    49         }
    50         
    51     }
    52 }
    View Code

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

     1 package com.dongnao.mytomcat;
     2 
     3 public class LoginServlet {
     4     public void service(Request request,Response response) throws Exception{
     5         String username=request.getParamName("username");
     6         String password=request.getParamName("pwd");
     7         if(username!=null&&username.equals("admin")&&password!=null&&password.equals("123")){
     8             response.writeHtmlFile("welcome.html");
     9         }else{
    10             response.writeHtmlFile("error.html");
    11         }
    12     }
    13 }
    View Code

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

     1 package com.dongnao.mytomcat;
     2 
     3 import java.io.BufferedReader;
     4 import java.io.FileNotFoundException;
     5 import java.io.FileReader;
     6 import java.io.IOException;
     7 
     8 /**
     9  *读取文件的工具类
    10  * @author CYA
    11  *
    12  */
    13 public class FileUtils {
    14     /**
    15      * 工具类
    16      */
    17     public static String getFileContent(String path){
    18         StringBuffer sb=new StringBuffer();
    19         FileReader fr=null;
    20         BufferedReader br=null;
    21         try {
    22              fr=new FileReader(path);
    23              br=new BufferedReader(fr);
    24              String line=null;
    25              while((line=br.readLine())!=null){
    26                  sb.append(line);
    27              }
    28         } catch (Exception e) {
    29             e.printStackTrace();
    30         } finally{
    31             try {
    32                 br.close();
    33                 fr.close();
    34             } catch (IOException e) {
    35                 e.printStackTrace();
    36             }    
    37         }
    38         return sb.toString();
    39     }
    40 }
    View Code
  • 相关阅读:
    struct xxx enum(在class下,在static void Main上)
    集合( Stack / Queue / Hashtable 都没有索引)
    集合(ArrayList)
    数组(for 循环+等量代换)
    类型(Math 、Datetime 、random )
    语句(语句分类及if语句)
    运算符分类、优先级
    基本类型转换及练习
    语言基础(项目结构、数据类型、变量、常量)
    进制转换(二进制、八进制、十进制与十六进制之间的相互转换)
  • 原文地址:https://www.cnblogs.com/softwarewebdesign/p/6054044.html
Copyright © 2011-2022 走看看