从百草园到三味书屋,从servlet到springmvc

Servlet:使用http协议在服务器与客户端之间通信的技术。是Socket的一种应用。

Socket:使用TCP/IP或者UDP协议在服务器与客户端之间进行传输的技术,是网络编程的基础。

Tomcat:一个servlet容器,它的底层是Socket编程(Process.java

springmvc: DispacherServlet

Tomcat简单实现

1.socket 循环获取请求,能得到输入流和输出流

ServerSocket serverSocket//实例化一个 ServerSocket 对象,表示通过服务器上的端口通信
 while(true) {
    Socket socket = serverSocket.accept(); //服务器调用 ServerSocket 类的 accept() 方法,该方法将一直等待,直到客户端连接到服务器上给定的端口
    socket.getInputStream();
    socket.getOutputStream();

}

2.inputStream转String,得到HTTP请求方法,还有URL

inputStreamStr.split("\n")[0];    //取出HTTP请求协议的首行
 method = httpHead.split("\\s")[0];     //按照空格进行分割,第一个是请求的方法
 url = httpHead.split("\\s")[1];      //按照空格进行分割,第二个是请求的路径

3. 配置一个map放url和servlet路径,也可以用一个Bean存放

map:"/index", "com.my.servlet.IndexServlet"
或者:

public class ServletMappingConfig {
    public static List<ServletMapping> servletMappingList = new ArrayList<>();

    static {
        servletMappingList.add(new ServletMapping("index", "/index", "com.my.servlet.IndexServlet"));
        servletMappingList.add(new ServletMapping("myblog", "/myblog", "com.my.servlet.MyBlog"));
    }
}

4. 根据配置的servlet路径反射调用里面的方法

1.public class IndexServlet extends MyServlet 
2.根据类路径反射创建实例,然后调用service方法
Class<MyServlet> myServletClass = (Class<MyServlet>)Class.forName(clazz);
            MyServlet myservlet = myServletClass.newInstance();
            myservlet.service(myRequest, myResponse);

5.返回,根据outputStream.write可以返回  CODE=200

  //将文本转换为字节流
    public void write(String content) throws IOException{
        StringBuffer httpResponse = new StringBuffer();
        httpResponse.append("HTTP/1.1 200 OK\n")      //按照HTTP响应报文的格式写入
                .append("Content-Type:text/html\n")
                .append("\r\n")
                .append("<html><head><link rel=\"icon\" href=\"data:;base64,=\"></head><body>")
                .append(content)          //将页面内容写入
                .append("</body></html>");
        outputStream.write(httpResponse.toString().getBytes());      //将文本转为字节流
        outputStream.close();
    }

猜你喜欢

转载自blog.csdn.net/x18094/article/details/115473876