java编写类似tomcat功能

花生 可爱的博主

时间: 2021-04-18 阅读: 129 字数:13184

{}
自己以前写的案例

模拟tomcat运行

tomcat主启动类

注册一个Socket服务来监听是否有访问此端口(tomcat默认8080)


public class MYtomcat {
    private static String URL = "";
    public static ServerSocket serverSocket=null; 
    private static Map<String, String> map =new HashMap<String, String>();
    private static ServletReAxi reAxi = new ServletReAxi();
    private static ServletRsAxi rsAxi = new ServletRsAxi();
    //预先加载的资源
    static {
        //设置默认访问静态资源
        map.put("index", "index.html");
        Properties properties = new Properties();
        try {
            properties.load(new FileInputStream(ServletRsAxi.WEB_ROOT+"\\se.properties"));
            Set set = properties.keySet();
            System.out.println(set);
            Iterator iterator =set.iterator();
            for (Object object : set) {
                String value = (String) properties.get(object);
                map.put((String)object, value);
            }        
        }  catch (Exception e) {
            e.printStackTrace();
        }
    }
//创建端口
    public ServerSocket getSersock() {
        if(serverSocket == null) {
            try {
                serverSocket = new ServerSocket(8081);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return serverSocket;
        
    }

    public static void main(String[] args) throws Exception {
        
        Thread thread1 = new Thread() {
            @Override
            public void run() {
                try {
                    MYtomcat.load(new MYtomcat().getSersock());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        
        thread1.start();
        
    }
    
    public static void load(ServerSocket serverSocket) throws Exception {
        System.out.println(map);    
                Socket socket = null;
                OutputStream os =null;
                InputStream is = null;
                OutputStreamWriter osw = null;
                System.out.println(ServletRsAxi.WEB_ROOT);
             while(true) {
             socket = serverSocket.accept();
             os =socket.getOutputStream();
             osw = new OutputStreamWriter(os,"UTF-8");
             is = socket.getInputStream();
             reAxi.input =is;
             rsAxi.os = osw;
             parse(is);//获取http协议,截取客户端要访问的资源名称,并将名称赋值给url
             
             if((URL.length() == 1 && URL.contains("/"))||URL.length() < 2) {
                 URL ="/"+map.get("index");
                 System.out.println(URL);
             }
             if(URL.contains(".")) {
                 System.out.println("静态资源");
                 senddStaticResoure(osw);//发送资源
             }else {
                 System.out.println("动态资源");
                 sendreRoure(osw,is);
             }
             osw.close();
             is.close();
             os.close();
             socket.close();
             }
    }
    //发送动态资源
    private static void sendreRoure(OutputStreamWriter os,InputStream is) throws Exception {
        System.out.println("动态资源截断/前:"+URL);
        String indexOf = URL.substring(1, URL.length());
        System.out.println("动态资源截断/后:"+indexOf);
        if(map.containsKey(indexOf)) {
            rsAxi.head();
            String value = map.get(indexOf);
            Class clazz = Class.forName(value.trim());
            Object newInstance = clazz.newInstance();
            Method init = clazz.getMethod("init");
            Method destry = clazz.getMethod("destry");
            Method service = clazz.getDeclaredMethod("service",ServletRsAxi.class,ServletReAxi.class);
            init.invoke(newInstance);
            service.invoke(newInstance, rsAxi,reAxi);
            destry.invoke(newInstance);
        }else {
            rsAxi.oror();
        }
    }
    //发送静态资源
    private static void senddStaticResoure(OutputStreamWriter os) throws IOException {
        rsAxi.senddStaticResoure(URL);
    }
    private static void parse(InputStream osw) throws IOException {

        URL = reAxi.parseURl();
        System.out.println(reAxi.getMap().size());
    }
}

ServletReAxi类 (Request)


public class ServletReAxi {
    public static InputStream input;
    public static String Encoder="UTF-8";
    public static Map<String, String[]> map =new HashMap<String, String[]>();
    public static String method;
    public static String Htmlall;
    /**
     *     获取浏览器发送的全部数据
     * @return
     * @throws IOException
     */
    public StringBuffer getAll() throws IOException {
        StringBuffer contextBuffer =new StringBuffer(2048);
        byte[] buffer = new byte[2048];
        int i = -1;
        i = input.read(buffer);
        for (int j = 0; j < i; j++) {
            contextBuffer.append((char)buffer[j]);
        }
        String string = contextBuffer.toString();
        if(string.length()>4) {
        method =string.substring(0,4).trim();
        }
        Htmlall = contextBuffer.toString();
        return contextBuffer;
    }
    public String gethtmlall() {
        return Htmlall;
    }
    public void SetURLEncoder(String str) {
        Encoder = str;
    }
    public String getMethod() {
        return method;
    }
    //获取带参完整的url
    public String parseURl(StringBuffer string) {
        
        String url = "";
        for (int i = 0; i < string.length(); i++) {
            if(string.charAt(i) == ' ') {
                System.out.println(string.charAt(i));
                for (int j = i+1; j < string.length(); j++) {
                    if(string.charAt(j) == ' ') {
                        break;
                    }
                    url+=string.charAt(j);
                }
                break;
            }
            
            
        }
        return url;
    }
    
    //获取不带参数的url
    public String parseURl() throws IOException {
        StringBuffer all = getAll();
        String parseURl = parseURl(all);
        int indexOf = parseURl.indexOf("?");
        String[] split2 = parseURl.split("=");
        System.out.println("方法:"+method);
        if(indexOf!=-1&&split2.length>1)
        {
            String substring = parseURl.substring(0,indexOf);
            String pString=null;
            try {
                
                pString = parseURl.substring(indexOf+1,parseURl.length());
            } catch (Exception e) {
                System.out.println("get请求参数不正确");
            }
                setMap(pString);
            return substring;
        }
        if("POST".equals(method)) {
            String[] split = all.toString().split("\r\n");
            String string;
            try {
                string = split[split.length-1];
            } catch (Exception e) {
                string=null;
                System.out.println("post请求参数不正确");
            }
            System.out.println("post参数:"+string);
            setMap(string);
        }
        return parseURl;
        
    }
    public Map<String, String[]> getMap() {
            return map;
    }
    
    
    
    
    //将参数存入map
    private void setMap(String str) {
        if(str!=null) {
            String[] split = str.split("&");
            
            for (int i = 0; i < split.length; i++) {
                String[] sp = split[i].split("=");
                String a= sp[1];
                for (int j = i+1; j < split.length; j++) {
                    String[] split3 = split[i].split("=");
                    String[] split4 = split[j].split("=");
                    String string2 = split3[0];
                    String string3 = split4[0];
                    if(string2.equals(string3)){
                        String[] split2 = split[j].split("=");
                        a+=","+split2[1];
                        i=j;
                    }
                    
                }
                String[] split2 = split[i].split("=");
                map.put(split2[0], a.split(","));
            }
        }
        
    }
    
    
    
    public String getName(String str) {
        String[] strings = map.get(str);
        if(strings != null) {
            try {
                //解码并返回
                return URLDecoder.decode(strings[0], Encoder);
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }
    
    
    public String[] getNames(String str) {
        String[] strings = map.get(str);
        if(strings != null) {
            return strings;
        }
        return null;
    }
}

ServletRsAxi 类 (Response)

public class ServletRsAxi {
    public static OutputStreamWriter os;
    public static String contentType="text/html;charset=UTF-8";
    public static String WEB_ROOT = System.getProperty("user.dir")+"\\"+"WebContent";//项目的绝对路径
    private static String URL = "";
    
    public void SetContentType(String str) {
        contentType =str;
    }
    public  void head() throws IOException {
         os.write("HTTP/1.1 200 OK\n");//状态码
         os.write("Content-Type:"+contentType+"\n");//编码格式,文件类型
         os.write("Server:Axidetomcat/1.1\n");//服务器
         os.write("\n\n");//空行
    }
    public void oror() throws IOException {
         os.write("HTTP/1.1 404 not found\n");//状态码
         os.write("Content-Type:text/html;charset=UTF-8\n");//编码格式,文件类型
         os.write("Server:Axidetomcat/1.1\n");//服务器
         os.write("\n\n");//空行
         os.write("<html>");
         os.write("<head>");
         os.write("<style>");
         os.write("h1{color:red;}");
         os.write("</style>");
         os.write("<title> 小王八犊子</title>");
         os.write("</head>");
         os.write("<body>");
         os.write("<h1>小王八犊子,找不到页面!</h1>");
         os.write("</body>");
         os.write("</html>");
         os.flush();
         os.close();
    }
    //发送静态资源
        public void senddStaticResoure(String URL) throws IOException {
            
            char[] buffer = new char[2048];
            FileInputStream fis =null;
            File file = new File(WEB_ROOT,URL); 
            InputStreamReader is = null;
            if(file.exists()) {
                head();
                 fis =new FileInputStream(file);
                 is =new InputStreamReader(fis,"UTF-8");
                 int ch =is.read(buffer);
                 while(ch != -1) {
                     os.write(buffer,0,ch);
                    ch =is.read(buffer);
                 }
                 os.flush();
                 os.close();
            }else {
                oror();
             }
        }
        public OutputStreamWriter getwriter() {
            return os;
        }
        public String getpath() {
            return WEB_ROOT;
        }
}

Servlet 接口

package com.axi.servlet;

import java.io.InputStream;
import java.io.OutputStreamWriter;

public interface Servlet {
public void init();
public void service(ServletRsAxi rsAxi,ServletReAxi reAxi);
public void destry();
}

测试类

package com.axi.servlet;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Bservlet implements Servlet {

    @Override
    public void init() {
        System.out.println("init...................");
    }

    @Override
    public void service(ServletRsAxi rsAxi,ServletReAxi reAxi) {
        
        System.out.println("service...................");
        String name = reAxi.getName("user");
        System.out.println(name);
        try {
            String all = reAxi.gethtmlall();
            System.out.println(all);
            rsAxi.getwriter().write("b========user"+name+"=========service");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void destry() {
        System.out.println("destry...................");
    }

}
本文章网址:https://www.sjxi.cn/detil/98d3a285fc354e75ae71dc73e25f21d5

最新评论

当前未登陆哦
登陆后才可评论哦

湘ICP备2021009447号