Servlet life cycle and processing Http requests and responses

  • servlet life cycle:

 

   1. The container starts and loads the servlet;

   2. Call the init() method to initialize the servlet;

   3. When the request comes, call the service() method to process the request and send the response;

   4. Call the destroy() method to destroy the servlet;

 

 

  • servlet processing Http response

           Let's take a look at the response information structure of http, including: status line, response header, blank line, message body;

           The meaning of each status code in the status line:

                      100-199: message;

                      200-299: The response is successful;

                      300-399: page redirection;

                      400-499: An error occurred on the client side;

                      500-599: An error occurred on the server side;

            We can also set the status code manually: response . setError (status code);

 

            Set the response header: response .setHeader(key, value);

 

            Set the message body (commonly used):

                       1. Transfer text: response .getWriter();

                       2. Transfer binary files: response .getOutputStream();

 

            Request redirection: response .sendRedirect();

            Redirection principle: When a request comes, if it wants to be redirected, the server will send a 302 status code in the status line, and send a location response header. After the client gets a 302 status code, it will modify the address bar to The location of the response header, and then send a request again, and the client sends two requests during the whole process;

 

  • servlet handles Http requests

              Let's take a look at the HTTP request information structure including: request line, request header, blank line, message body;

 

              Get property method: request.getParemeter(name); request.getParemeterValues(name);

 

              Internal forwarding:

                  RequestDispather dis = request.getRequestDispather("forwarding address");

                  dis.include(request,response);

                  dis.forward(request,response);

 

              Method 1 to correct garbled characters: Uniform character encoding in the page: < %@page ContentType="text/html;charset=utf-8" % >

              Method 2 to correct garbled characters: Example: String name=request.getParemeter("name");

                                           byte[] bt = name.getBytes("ISO8859-1");

                                           name = new String(bt,"gbk");

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326606105&siteId=291194637