Java Web VI: other related problems of Servlet

Servlet 2: some other related problems of Servlet

1, Set code

  1. get request method

    Based on tomcat8, transcoding is not required

    To send Chinese data before tomcat8, the following transcoding operations are required

    String fname = req.getParameter("fname");
    // 1. Break the string into byte arrays
    byte[] bytes = fname.getBytes("ISO-8859-1");
    // 2. Reassemble the byte array into a string according to the set encoding
    fname = new String(bytes,"UTF-8");
    
  2. post request mode
    req.serCharacterEncoding("UTF-8");
    

    Note: this code must be before all actions to get parameters

2, Inheritance relationship of Servlet

  1. Inheritance relationship
    javax.servlet.Servlet	Interface
        javax.servlet.GenericServlet	abstract class
        	javax.servlet.http.HttpServlet    Abstract subclass		
    
  2. correlation method
    The focus is on service methods

    ① javax.servlet.Servlet interface

    void init(config)  Initialization method
    void service(ServletRequest var1, ServletResponse var2)  Service method
    void destory()  Destruction method
    

    ② javax.servlet.GenericServlet abstract class

    public abstract void service(ServletRequest var1, ServletResponse var2)   Still an abstract method
    

    ③ javax.servlet.http.HttpServlet Abstract subclass

    protected void service(HttpServletRequest req, HttpServletResponse resp){
        // 1. Acquisition request method
        String method = req.getMethod();
        // 2. Execute different methods according to different request methods
        if (method.equals("GET")) {
            this.doGet(req, resp);
        } else if (method.equals("HEAD")) {
            this.doHead(req, resp);
        } else if (method.equals("POST")) {
            this.doPost(req, resp);
        } else if (method.equals("PUT")) {
            this.doPut(req, resp);
        } else if (method.equals("DELETE")) {
            this.doDelete(req, resp);
        } else if (method.equals("OPTIONS")) {
            this.doOptions(req, resp);
        } else if (method.equals("TRACE")) {
            this.doTrace(req, resp);
        } else {
            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[]{method};
            errMsg = MessageFormat.format(errMsg, errArgs);
            resp.sendError(501, errMsg);
        }
    }
    
    // 3.do methods are similar
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)  {
            String protocol = req.getProtocol();
            String msg = lStrings.getString("http.method_post_not_supported");
            if (protocol.endsWith("1.1")) {
                resp.sendError(405, msg);
            } else {
                resp.sendError(400, msg);
            }
    
        }
    
  3. Summary

    ① Inheritance relationship: httpservlet - > genericservlet - > Servlet

    ② The core method in Servlet: init(), service(), destroy()

    ③ Service method service(): when a request comes, the service method will respond automatically (actually called by tomcat container). In HttpServlet, the method of the request will be automatically analyzed to determine which method starting with do to call.

    ④ These do methods are 405 implementation style by default. Therefore, when creating a new Servlet, we will consider the request type and decide to rewrite the corresponding do method

3, Life cycle of Servlet

  1. definition

    The whole process from appearance to extinction corresponds to the above three core methods, which are maintained by tomcat

  2. Default

    When receiving the request for the first time, the Servlet will instantiate (call the construction method), initialize (call the init method), and then the service (call the service method)

    From the second request, every time is a service

    When the container closes, all servlet instances in it are destroyed

    2.1 service method of testing life cycle
    package com.atguigu.servlets;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.*;
    import java.io.IOException;
    
    /**
     * @author e_n
     * @version 1.0.0
     * @ClassName Web_Cycle.java
     * @Description
     * @CreateTime 2022/03/01 11:00
     */
    public class Web_Cycle extends HttpServlet {
        public Web_Cycle() {
            System.out.println("constructor ");
        }
    
        @Override
        public void init() throws ServletException {
            System.out.println("Initial method");
        }
    
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("Service method");
        }
    
        @Override
        public void destroy() {
            System.out.println("Destruction method");
        }
    }
    
    2.2 configuring web XML file
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0">
        
        <servlet>
            <servlet-name>Web_Cycle</servlet-name>
            <servlet-class>com.atguigu.servlets.Web_Cycle</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>Web_Cycle</servlet-name>
            <url-pattern>/demo1</url-pattern>
        </servlet-mapping>    
    </web-app>
    
    2.3 configuring tomcat

  3. Situation description

    In tomcat, only one Servlet instance will be created, and all requests will be responded by this instance

    By default, tomcat will instantiate and initialize the first request. In order to improve the startup speed of the system, we should set the initialization time of the Servlet

  4. Servlet initialization timing
    <!-- load-on-startup The smaller the number in, the higher the start-up, and the minimum value is 0 -->
    <servlet>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
  5. Servlet in container: singleton, thread unsafe

    Singleton: all requests are responded by the same instance

    Thread unsafe: a thread needs to make logical judgment according to a member variable in this instance. But at some point in the middle, another thread changes the member variable

    **Therefore: * * try not to define member variables in servlet s. If a member variable must be defined, do not modify the value of the member variable or make logical judgment based on the value of the member variable

4, Http protocol

  1. HTTP: HyperText Transfer Protocol
  2. Http is stateless
  3. Http request
    Request line

    It contains three information: the way of request; The URL of the request; Requested agreement (generally HTTP 1.1, HTTP 2.0 withdrawn in 2015)

    Request header

    Contains messages that the client tells the server. For example: the model and version of the browser, the content type I can receive, and the content type I send you

    Request body

    get method: there is no request body, but there is a queryString

    post mode: with request body, form data

    json mode: with request body: payload

  4. Http response
    Response line

    Contains three messages: 1 agreement; 2. Response status code (200); 3. Response status (ok)

    Response header

    Including the information of the server; Information sent by the server to the browser (media type, code, content length, etc.)

    Responder

    Actual content of response

5, session

  1. Http is stateless

    Concept: the server cannot judge whether the two requests are sent by the same client or different clients

    Practical example: the first request is to add goods to the shopping cart, and the second request is to check out. If the server cannot distinguish whether the two requests are sent by the same user, there will be confusion. You may have checked out someone else's shopping cart

    Solution: session tracking technology

  2. Session tracking technology

    2.1 the client sends a request to the server for the first time, and the server obtains the session. If it cannot obtain it, it creates a new one, and then sends it to the client accordingly

    2.2 the next time the client sends a request to the server, it will bring the sessionId to the server. When the server obtains it, it will judge which client's request is the same as the last one, so as to distinguish different clients

    // Common API s
    // 1. Get the current session. If not, create a new session
    request.getSession();
    request.getSession(true);  
    // 2. Get the current session. If not, null will be returned and no new session will be created
    request.getSession(false); 
    // 3. Obtain sessionId, which is unique in the world
    session.getId();
    // 4. Judge whether the current session is new
    session.isNew();
    // 5. The inactive interval of session is 1800 seconds (i.e. 30 minutes) by default. For example, in the banking system, if you don't do anything every 30 minutes, you need to log in again
    sesseion.getMaxInactiveInterval();
    sesseion.setMaxInactiveInterval();
    // 6. Force the session to expire immediately
    session.invalidate();
    ...
    

6, Server Internal forwarding and client redirection

  1. Server Internal forwarding

    Process: a request response process. For the client, the client does not know how many times it has been forwarded internally

    Result: the address bar has not changed

    code:
    public class Demo6Servlet  extends HttpServlet {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("demo6");
            // Server Internal forwarding
            req.getRequestDispatcher("demo7").forward(req,resp);
        }
    }
    
    public class Demo7Servlet extends HttpServlet {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("demo7");
        }
    }
    
    flow chart:

  2. Client redirection

    Process: the process of responding to two requests. The client knows that the requested URL has changed

    Result: the address bar has changed

    code:
    public class Demo6Servlet  extends HttpServlet {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("demo6");
            // Relocation
            resp.sendRedirect("demo7");
        }
    }
    
    public class Demo7Servlet extends HttpServlet {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("demo7");
        }
    }
    
    flow chart:

Keywords: Java css3 html css

Added by priya_cks on Wed, 02 Mar 2022 13:15:40 +0200