Geek

博客园 首页 新随笔 联系 订阅 管理

 

 访问网址时的请求,请求的内容就大概是这个样子了,那么这个时候要表示这个请求。

package tomcat;

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

/**
 * @Author lyr
 * @create 2020/7/15 21:34
 */
public class IRequest {
    private String url;

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

    private String method;
    public IRequest(InputStream inputStream) throws IOException {
        String request = "";
        byte[] bytes = new byte[1024];
        int len = 0;
        if((len = inputStream.read(bytes))>0) {
            request = new String(bytes,0,len);
        }
        System.out.println("request Body :-> \r\n"+request);
        String httpHead = request.split("\n")[0];
        url = httpHead.split("\\s")[1];
        method = httpHead.split("\\s")[0];
        System.out.println(this);
    }

}

 

package tomcat;

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

/**
 * @Author lyr
 * @create 2020/7/15 21:46
 */
public class IResponse {
    private OutputStream outputStream;
    public IResponse(OutputStream outputStream) {
        this.outputStream = outputStream;
    }
    public void write(String content) throws IOException {
        StringBuilder sb = new StringBuilder();
        sb.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(sb.toString().getBytes());
        outputStream.close();
    }

}

 

 

简单定义 Servlet接口

package tomcat;

/**
 * @Author lyr
 * @create 2020/7/15 21:51
 */
public abstract class IServlet {
    /**
     * @param request
     * @param response
     */
    public abstract void doGet(IRequest request,IResponse response);

    /**
     * @param request
     * @param response
     */
    public abstract void doPost(IRequest request,IResponse response);

    public void service(IRequest request,IResponse response) {
        if(request.getMethod().equalsIgnoreCase("POST")) {
            doPost(request,response);
        }else if(request.getMethod().equalsIgnoreCase("GET")) {
            doGet(request,response);
        }
    }

}

 

 

实现代码:

package tomcat.impl;

import tomcat.IRequest;
import tomcat.IResponse;
import tomcat.IServlet;

import java.io.IOException;

/**
 * @Author lyr
 * @create 2020/7/15 21:56
 */
public class HelloServletImpl extends IServlet {
    /**
     * @param request
     * @param response
     */
    @Override
    public void doGet(IRequest request, IResponse response) {
        try {
            response.write("hello world");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @param request
     * @param response
     */
    @Override
    public void doPost(IRequest request, IResponse response) {
        try {
            response.write(" hello post   ");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

 

然后把 URL 和 解析的 Servlet绑定到一起。

 

 

package tomcat;

/**
 * @Author lyr
 * @create 2020/7/15 21:59
 */
public class ServletMapping {
    private String servletName;
    private String url;
    private Class<?> clazz;

    public ServletMapping(String servletName, String url, Class<?> 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 Class<?> getClazz() {
        return clazz;
    }

    public void setClazz(Class<?> clazz) {
        this.clazz = clazz;
    }
}

 

package tomcat;

import tomcat.impl.HelloServletImpl;

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

/**
 * @Author lyr
 * @create 2020/7/15 22:01
 */
public class ServletMappingConfig {
    public static List<ServletMapping> servletMappingList
            = new ArrayList<>();
    static {
        servletMappingList.add(new ServletMapping("helloServlet","/hello", HelloServletImpl.class));
        servletMappingList.add(new ServletMapping("helloServlet","/aa",HelloServletImpl.class));
    }
}

 

监听端口,然后运行程序

package tomcat;

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;

/**
 * @Author lyr
 * @create 2020/7/15 22:03
 */
public class TomcatServer {
    private int port = 8080;
    private Map<String,Class<?>> urlServletMap = new HashMap<>();

    public TomcatServer(int port) {
        this.port = port;
    }
    public void start() {
        initServletMapping();
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("tomcat is running");
            while (true) {
                Socket socket = serverSocket.accept();
                InputStream is = socket.getInputStream();
                OutputStream os = socket.getOutputStream();
                dispatch(new IRequest(is),new IResponse(os));
                socket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    private void initServletMapping() {
        for(ServletMapping s: ServletMappingConfig.servletMappingList) {
            urlServletMap.put(s.getUrl(),s.getClazz());
        }

    }
    private void dispatch(IRequest request,IResponse response) {
        Class<?> clazz = urlServletMap.get(request.getUrl());
        System.out.println(clazz);
        try {

            // Class<IServlet> servletClazz = (Class<IServlet>)clazz;
            if(clazz!=null) {
                IServlet servlet = (IServlet) clazz.newInstance();
                servlet.service(request,response);
            }
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
    }

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

 

浏览器请求的内容就是这些了

 

posted on 2020-07-15 23:37  .geek  阅读(137)  评论(0编辑  收藏  举报