hz90 / diy

0 stars 0 forks source link

mini Tomcat #1

Open hz90 opened 5 years ago

hz90 commented 5 years ago

package com.mytomcat;

import java.io.IOException; import java.io.InputStream;

public class FRequest {

private String url;
private String method;

public FRequest(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);
    }

    String httpHead = httpRequest.split("\n")[0];
    url = httpHead.split("\\s")[1];
    method = httpHead.split("\\s")[0];
    if (url.startsWith("/") && !url.startsWith("/favicon.ico")
            && ("GET".equalsIgnoreCase(method) || "POST".equalsIgnoreCase(method))) {

    } else {
        String[] strhead = httpRequest.split("\n");
        int broswer = 0;
        for (String string : strhead) {
            if (string.startsWith("User-Agent:") && string.toLowerCase().indexOf("chrome") > 0) {
                //this is chrome browser
                broswer = 1;
            }
            if (broswer == 1) {
                if (string.toLowerCase().startsWith("referer")) {
                    url = string.substring(string.lastIndexOf("/")).trim();
                }
            }
            if (string.toLowerCase().startsWith("get ") || string.toLowerCase().startsWith("post ")) {
                method = string.substring(0, 4).trim();
            }

        }
    }

    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;
}

}


package com.mytomcat;

import java.io.IOException; import java.io.OutputStream;

public class FReponse { private OutputStream outputStream;

public FReponse(OutputStream outputStream) {
    this.outputStream = outputStream;
}

public void write(String content) throws IOException {
    StringBuffer httpresponse = new StringBuffer();
    httpresponse.append("HTTP/1.1 200 OK\n")
            .append("Content-Type:  text/html\n")
            .append("\r\n")
            .append("<html><body>")
            .append(content)
            .append("</body></html>");
    outputStream.write(httpresponse.toString().getBytes());
    outputStream.close();

}

}


package com.mytomcat;

public abstract class FServlet { public abstract void doPost(FRequest fRequest, FReponse fReponse);

public abstract void doGet(FRequest fRequest, FReponse fReponse);

public void service(FRequest fRequest, FReponse fReponse) {

    if ("POST".equalsIgnoreCase(fRequest.getMethod())) {
        doPost(fRequest, fReponse);
    } else if ("GET".equalsIgnoreCase(fRequest.getMethod())) {
        doGet(fRequest, fReponse);
    }
}

}


package com.mytomcat;

import java.io.IOException;

public class HelloWorldServlet extends FServlet {

@Override
public void doPost(FRequest fRequest, FReponse fReponse) {
    try {
        fReponse.write("post hello my tomcat ..........");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

@Override
public void doGet(FRequest fRequest, FReponse fReponse) {
    try {
        fReponse.write("get hello my tomcat ..........");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}


package com.mytomcat;

public class ServletMapping { private String servletName; private String url; private String clazz;

public ServletMapping(String servletName, String url, String clazz) {
    this.servletName = servletName;
    this.url = url;
    this.clazz = clazz;
}

public String getServletName() {
    return servletName;
}

public void setServletName(String servletName) {
    this.servletName = servletName;
}

public String getUrl() {
    return url;
}

public void setUrl(String url) {
    this.url = url;
}

public String getClazz() {
    return clazz;
}

public void setClazz(String clazz) {
    this.clazz = clazz;
}

}


package com.mytomcat;

import java.util.ArrayList; import java.util.List;

public class ServletMappingConfig { public static List servletMappinglist=new ArrayList(); static { servletMappinglist.add(new ServletMapping("hello", "/fly", "com.mytomcat.HelloWorldServlet")); } }


package com.mytomcat;

import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.Map;

public class FTomcat { private int port = 8080; private Map<String, String> urlservletMap = new HashMap<>();

public FTomcat(int port) {
    this.port = port;
}

public void start() {
    initServletmapping();
    ServerSocket serverSocket = null;
    try {
        serverSocket = new ServerSocket(port);
        System.out.println("tomcat is start.........");
        while (true) {

            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream();
            FRequest fRequest = new FRequest(inputStream);
            FReponse fReponse = new FReponse(outputStream);
            dispatch(fRequest, fReponse);
            socket.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

private void initServletmapping() {
    for (ServletMapping servletMapping : ServletMappingConfig.servletMappinglist) {
        urlservletMap.put(servletMapping.getUrl(), servletMapping.getClazz());
    }
}

private void dispatch(FRequest fRequest, FReponse fReponse) {
    String clazz = urlservletMap.get(fRequest.getUrl());

    try {
        Class<FServlet> fServletClass = (Class<FServlet>) Class.forName(clazz);
        FServlet fServlet = fServletClass.newInstance();
        fServlet.service(fRequest, fReponse);
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

}

public static void main(String[] args) {
    new FTomcat(8080).start();
}

}