Java Web:Servlet原理

一、什么是Servlet

是一种Web服务器端编程技术。
是实现了特殊接口的Java类。
由支持Servlet的Web服务器调用和启动运行。
一个Servlet负责对应的一个或一组URL访问请求,并返回相应的响应内容。
在这里插入图片描述

二、Servlet和http请求

1、http请求格式

在这里插入图片描述

2、http请求方式

在这里插入图片描述
get请求和post请求区别:

  1. get请求参数是会显示到地址栏的,post不显示。
  2. get请求不安全,post请求安全。
  3. get请求参数长度限制,post不限制。

3、http状态响应吗

在这里插入图片描述
在这里插入图片描述

三、Servlet服务

1、servlet和Tomcat请求关系:

在这里插入图片描述

2、简单撸一个Tomcat

package com.bobo;

import java.io.InputStream;

public class MyRequest {
    //客户端请求类型
    private String requestType;
    //客户端请求URL
    private String requestUrl;

    public MyRequest(InputStream inputStream) throws Exception {
        byte[] bytes = new byte[1024];
        int len = inputStream.read(bytes);
        String text = new String(bytes, 0, len);
        String firstLine = text.split("\n")[0];
        String[] firstTextArray = firstLine.split(" ");
        this.requestType = firstTextArray[0];
        this.requestUrl = firstTextArray[1];
    }

    public String getRequestType() {
        return requestType;
    }

    public void setRequestType(String requestType) {
        this.requestType = requestType;
    }

    public String getRequestUrl() {
        return requestUrl;
    }

    public void setRequestUrl(String requestUrl) {
        this.requestUrl = requestUrl;
    }
}

package com.bobo;

import java.io.OutputStream;

public class MyResponse {
    private OutputStream outputStream;

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

    public void write(String str) throws Exception{
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("HTTP/1.0 200 ok\n")
                .append("Context-type:text/html\n")
                .append("\r\n")
                .append("<html>")
                .append("<body>")
                .append("<h1>"+str+"</h1>")
                .append("</body>")
                .append("</html>");
        outputStream.write(stringBuilder.toString().getBytes());
        outputStream.flush();
        outputStream.close();
    }
}

package com.bobo;

public abstract class MyHttpServlet {

    private static final String REQUEST_GET="GET";
    private static final String REQUEST_POST="POST";

    public abstract void doGet(MyRequest request,MyResponse response) throws Exception;
    public abstract void doPost(MyRequest request,MyResponse response) throws Exception;

    public void service(MyRequest request,MyResponse response) throws Exception{
        if (REQUEST_GET.equals(request.getRequestType())){
            doGet(request,response);
        }else {
            doPost(request,response);
        }
    }
}

package com.bobo;

public class MyServlet extends MyHttpServlet {
    @Override
    public void doGet(MyRequest request, MyResponse response) throws Exception {
        response.write("MyTomcat Get");
    }

    @Override
    public void doPost(MyRequest request, MyResponse response) throws Exception {
        response.write("MyTomcat Post");
    }
}

package com.bobo;

import java.util.HashMap;

public class MyMapping {
    public static HashMap<String,String> mapping=new HashMap<>();
    static {
        mapping.put("/myTomcat","com.bobo.MyServlet");
   }
   public static HashMap<String,String> getMapping(){
        return mapping;
   }
}

package com.bobo;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyService {
    public static void startService(int port) throws Exception{
        //服务器端套接字
        ServerSocket serverSocket=new ServerSocket(port);
        //客户端套接字
        Socket socket=null;
        while (true){
            socket=serverSocket.accept();

            //输入输出流
            InputStream inputStream=socket.getInputStream();
            OutputStream outputStream=socket.getOutputStream();

            //初始化请求响应类
            MyRequest myRequest=new MyRequest(inputStream);
            MyResponse myResponse=new MyResponse(outputStream);

            //找到合适的applet
            String classString = MyMapping.getMapping().get(myRequest.getRequestUrl());
            System.out.println(classString);
            if (classString!=null){
                Class<MyHttpServlet> clazz=(Class<MyHttpServlet>) Class.forName(classString);
                MyHttpServlet myHttpServlet=clazz.newInstance();
                myHttpServlet.service(myRequest,myResponse);
            }
        }
    }

    public static void main(String[] args) {
        try {
            startService(10087);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在这里插入图片描述

四、Servlet访问流程

url:http://localhost:8080/firstweb/first

组成:

服务器地址:端口/虚拟项目名/servlet的别名
uri:虚拟项目名/servlet别名

过程:浏览器发送请求到服务器,服务器根据请求URL地址中的URI信息在webapps目录下找到对应的项目文件夹,然后再web.xml中检索对应的servlet,找到后调用并执行servlet。

在这里插入图片描述
servlet从第一次请求时创建,到关闭服务器时销毁,中间多次请求只会存在一个servlet在内存中。当在web.xml中配置了1,在开启tomcat时就会创建servlet实例。

  • Service方法:不管是get还是post请求方式,如果service方法存在,则优先执行service方法。
  • doGet方法:在没有service的情况下,如果是get请求,调用doGet方法。
  • doPost方法:在没有service的情况下,如果是post请求,调用diPost方法。
发布了79 篇原创文章 · 获赞 147 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/u013277209/article/details/104856391