JavaWeb-Servlet basic summary implementation principle (a bit rough, I hope you can correct me)

Servlet (Getting Started)

Servlet: a small program running on the server

​ Servlet is an interface that defines the rules for java classes to be accessed by the browser (tomcat recognition)

step:

  1. Create a project

  2. Define a class and implement the interface

    public class ServletDemo01 implements Servlet
    
  3. Abstract method to implement interface

  4. Configure Servlet file

    Configuration file in web.xml

<servlet>
    <servlet-name>ServletDemo01</servlet-name>
    <servlet-class>cn.lsk.Servlet.ServletDemo01</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ServletDemo01</servlet-name>
    <url-pattern>/sd</url-pattern>
</servlet-mapping>

Insert picture description here

Principle of execution:

  1. When the server receives the request from the client browser, it will parse the request URL path to obtain the resource path of the accessed servlet.
  2. Look up the web.xml file and see if there is a corresponding tag body content.
  3. If so, find the corresponding full class name
  4. Tomcat will load the bytecode file into memory and create its object
  5. Call its method

Servlet method (life cycle)

  1. Create: Execute the init method only once

    When was the servlet created?

    ​ By default, the Servlet is created when it is accessed for the first time

    ​ You can also configure the creation timing of the execution Servlet (in Web.xml)

    ​ If the value is positive, it will be created when the server starts

    ​ If it is a negative number, it is created when it is accessed for the first time

    <load-on-startup> -4 </load-on-startup>
    

    The init method of Servlet is executed only once, indicating that a Servlet has only one object in the memory, and the Servlet is singleton

    ​ When multiple users access at the same time, there may be thread safety issues

    ​ Solution: try not to define member variables in the Servlet, if you define it, do not modify the value

  2. Provide service: execute Servlet method, execute multiple times

    It will be executed once for every visit

  3. Destroy: Execute the destroy method, only once

    Only the server is shut down normally, the destroy method will be executed

public class ServletDemo02 implements Servlet {
    
    
    /**
     * 初始化方法
     *  在Servlet被创建时,执行。只会执行一次
     */
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
    
    
        System.out.println("我被创建了,我只执行一次");
    }

   /**
    * 获取ServletConfig对象
    * ServletConfig: Servlet的配置对象
    * /
    @Override
    public ServletConfig getServletConfig() {
        return null;
    }

     /*
     * 提供服务的方法
     * 每一次Servlet被访问时,执行。执行多次
     *
     * */
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
    
    
        System.out.println("Hello WDNMD");
    }
    /*
    * 获取Servlet的一些信息,版本,作者等等···
    *
    * */
    @Override
    public String getServletInfo() {
    
    
        return null;
    }

    /*
    * 销毁方法
    * 在服务器正常关闭时,执行,执行一次
    *
    * */
    @Override
    public void destroy() {
    
    
        System.out.println("GG");
    }
}

The first execution:

Insert picture description here

If we refresh

Insert picture description here

It can be seen serviceagain and call initinitialization method is performed only once

If we shut down the server normally

Insert picture description here

Servlet annotation configuration:

step:

  1. Create project

  2. Define a class to implement the interface

  3. Copy method

  4. Use @WebServlet annotation on the class for configuration

    @WebServlet("Resource Path")

@WebServlet("/sd3")
public class ServletDemo03 implements Servlet {
    
    
    /**
     * 初始化方法
     *  在Servlet被创建时,执行。只会执行一次
     */
    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
    
    
        System.out.println("我被创建了,我只执行一次");
    }

    /*
    * 获取ServletConfig对象
    * ServletConfig: Servlet的配置对象
    * */
    @Override
    public ServletConfig getServletConfig() {
    
    
        return null;
    }

     /*
     * 提供服务的方法
     * 每一次Servlet被访问时,执行。执行对此
     *
     * */
    @Override
    public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
    
    
        System.out.println("注解");
    }
    /*
    * 获取Servlet的一些信息,版本,作者等等···
    *
    * */
    @Override
    public String getServletInfo() {
    
    
        return null;
    }

    /*
    * 销毁方法
    * 在服务器正常关闭时,执行,执行一次
    *
    * */
    @Override
    public void destroy() {
    
    
        System.out.println("GG");
    }
}

Insert picture description here

Servlet architecture

Servlet (interface)

GenericServlet(Abstract class) He implements the Servlet interface

//部分源码
public abstract class GenericServlet implements Servlet, 
ServletConfig, 
Serializable {
    
    }

HttpServlet (abstract class) it inheritsGenericServlet

//部分源码
public abstract class HttpServlet extends GenericServlet {
    
    }

Let's look at the functions of the two abstract classes separately:

Let's not implement the Servlet interface but inherit GenericServlet

@WebServlet("/sd3")
public class ServletDemo04 extends GenericServlet {
    
    

    @Override
    public void service(ServletRequest servletRequest,
                        ServletResponse servletResponse)
            throws ServletException, IOException {
    
    


    }
}

Enter the GenericServlet source code, we can see: (only part of the source code)

public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {
    
    
    private static final long serialVersionUID = 1L;
    private transient ServletConfig config;

    public GenericServlet() {
    
    
    }
    
    //方法空实现  只有声明
    public void destroy() {
    
    
    }

    //方法空实现  只有声明
    public void init() throws ServletException {
    
    
    }
     
    public abstract void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;

}

We can see that he made empty implementations of other methods, and only abstracted one method is the ** service** method. So we inherit GenericServletonly rewrite servicemethod

HttpServlet

There is a service method in the Servlet method. What shall we do in the service in the future?

  1. Determine the request method

    String mehod = request.getMethod();

    if(“GET”.equals(mehod )){

    // get way to get data

    doGet();

    }else if(“POST”.equals(mehod )){

    // post data acquisition mode

    doPost();

    }

  2. retrieve data

    But our HttpServlet has written the above code for us

@WebServlet("/sd3")
public class ServletDemo05 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        super.doGet(req, resp);
        System.out.println("doGet");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        super.doPost(req, resp);
        System.out.println("doPost");
    }
}

Request through browser is get request

Insert picture description here

Access through the form is a Post request

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<form action="${pageContext.request.contextPath}/sd5" method="post">
    <input name="username">
    <input type="submit" value="提交">
</form>
</body>
</html>

Insert picture description here
Insert picture description here

Introduce comments

Insert picture description here

  1. If you choose Create Java EE 6 annotated class

    It creates a succession HttpServletofServlet

Insert picture description here

web.xml:

<servlet>
    <servlet-name>ServletDemo06</servlet-name>
    <servlet-class>cn.lsk.Servlet.ServletDemo06</servlet-class>
</servlet>
 //需要自己编写
<servlet-mapping>
    <servlet-name>ServletDemo06</servlet-name>
    <url-pattern>/sd6</url-pattern>
</servlet-mapping>

Guess you like

Origin blog.csdn.net/agood_man/article/details/108517752
Recommended