Basic learning of HTTP Hypertext Transfer Protocol

HTTP Hypertext Transfer Protocol

Concept: Hyper Text Tranfer Protocol

  • Transmission protocol: it defines that the communication between client and server is the format of sending data
  • characteristic:
    1. Advanced protocol based on TCP/IP
    2. Default port number: 80
    3. Based on request / response model: one request corresponds to one response
    4. Stateless: each request is independent of each other and cannot interact with data
  • Historical version:
    1. Each request response establishes a new connection
    2. Multiplex connection

Request message data format

  1. Request line

    • Request mode request url request protocol / version

    • GET/login.html HTTP/1.1

    • Request method:

      • There are seven request modes in HTTP protocol, and two are commonly used
        • GET:
          1. The request parameters are in the request line, after the url
          2. The length of the requested url is limited
          3. Not very safe
        • POST:
          1. The request parameter is in the request body
          2. There is no limit on the length of the requested url
          3. Relative safety
  2. Request header: the client browser tells the server some information

    1. Request header name: request header value
    2. Common request headers:
      1. User agent: the browser tells the server that I can access the version information of the browser you use
        • The header information can be obtained on the server side to solve the compatibility problem of the browser
      2. Referer: http://localhost:8080/MyApps/login.html
        • Tell the server where I (current request) come from
          • effect:
            1. Anti theft chain
            2. Statistics
  3. Request blank line

    1. Blank line: used to split the request header and body of the POST request.
  4. Request body (body)

    • Encapsulates the request parameters of the POST request message
  5. String format:

    POST /MyApps/ser03 HTTP/1.1
    Host: localhost:8080
    User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:95.0) Gecko/20100101 Firefox/95.0
    Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
    Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
    Accept-Encoding: gzip, deflate
    Content-Type: application/x-www-form-urlencoded
    Content-Length: 12
    Origin: http://localhost:8080
    Connection: keep-alive
    Referer: http://localhost:8080/MyApps/login.html
    Cookie: Idea-4311a65=5ac6d3b1-7c53-43e0-b438-60c6c2dbe879
    Upgrade-Insecure-Requests: 1
    Sec-Fetch-Dest: document
    Sec-Fetch-Mode: navigate
    Sec-Fetch-Site: same-origin
    Sec-Fetch-User: ?1
    
    USERNAME=ads
    

Response message data format

Request

  1. Principle of request object and response object

    1. The request and response objects are created by the server. Let's use them
    2. The request object is used to get the request message, and the response object is used to set the response message
  2. request object inheritance architecture

    • ServletRequest - Interface
    • Succession
    • HttpServletRequest - Interface
    • | realization
    • org.apache.catalina.connector.CoyoteInputStream class (Tomcat)
  3. request:

    1. Get request message data

      1. Get request line data

        • GET /MyApps/demo01?name=qin HTTP/1.1
        • method:
          1. GET request method: GET
            • String getMethod()
          2. Get virtual directory: / MyApps
            • String getContextPath()
          3. Get Servlet path: / demo1
            • String getServletPath()
          4. Get request parameters of get method: name=qin
            • String getQueryString()
          5. Get requested uri: / MyApps/demo1
            • String getRequestURI():/MyApps/demo1
            • StringBuffer getRequestURL():http://localhost/MyApps/demo1
            • URL: uniform resource locator: http://localhost/MyApps/demo1
            • URI: uniform resource identifier (wider range): / MyApps/demo1
          6. Get protocol and version HTTP/1.1
            • String getProtocol()
          7. Gets the IP address of the client
            • String getRemoteAddr()
      2. Get request header data

        • method:
          • String getHeader(String name): get the value of the request header through the name of the request header
          • Enumeration < string > getheadernames(): get all request header names
      3. Get request body data

        • Request body: only the POST request method can have a request body. The request parameters of the POST request are encapsulated in the request body

        • Steps:

          1. Get stream object

            • BufferedReader getReader(): gets the character input stream. Only character data can be manipulated

            • ServletInputStream getInputStream(): get byte input stream, which can operate on all types of data

            • regist.html

              <!DOCTYPE html>
              <html lang="en">
              <head>
                  <meta charset="UTF-8">
                  <title>register</title>
              </head>
              <body>
                  <form action="rd5" method="post">
                      <input type="text" placeholder="enter one user name" name="username">
                      <input type="text" placeholder="Please input a password" name="password"><br>
                      <input type="submit" value="submit">
                  </form>
              </body>
              </html>
              
            • RequestDemo5

              package com.web.request;
              
              import javax.servlet.ServletException;
              import javax.servlet.annotation.WebServlet;
              import javax.servlet.http.HttpServlet;
              import javax.servlet.http.HttpServletRequest;
              import javax.servlet.http.HttpServletResponse;
              import java.io.BufferedReader;
              import java.io.IOException;
              
              @WebServlet("/rd5")
              public class RequestDemo05 extends HttpServlet {
                  @Override
                  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              
                  }
              
                  @Override
                  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                      //Get request message body -- request parameters
              
                      //1. Get character stream
                      BufferedReader br = request.getReader();
                      //2. Read data
                      String line = null;
                      while ((line = br.readLine())!=null){
                          System.out.println(line);
                      }
                  }
              }  
              
              
          2. Then get the data from the stream object

    2. Other functions

      1. General method for obtaining request parameters (whether GET or POST):

        1. String getParameter(String name): get the parameter value according to the parameter name username = Qin & password = 123

        2. String getParameterValues(String name): get the array of parameter values according to the parameter name: Hobby = XX & Hobby = game

        3. Enumeration < string > getparameternames(): get the parameter names of all requests

        4. Map < string, string [] > getparametermap(): get the map set of all parameters

        5. Chinese garbled code problem

          @Override
          protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
                  //post get request parameters
                  // Get parameter value according to parameter name
          	    //1. Set the code of the request
                  request.setCharacterEncoding("UTF-8");
                  String username = request.getParameter("username");
                  System.out.println(username);
                  try {
                      response.setCharacterEncoding("GBK");
                  } catch (Exception e) {
                      e.printStackTrace();
                  }
                  response.getWriter().write(username);
              }
          }
          
          • Get mode: Tomcat 8 has solved the problem of garbled code in get mode

          • post mode: garbled code

            • Solution: set the encoding of the request before getting the parameters

              //1. Set the code of the request
              request.setCharacterEncoding("UTF-8");
              
      2. Request forwarding: a resource jump mode within the server

        1. Steps:
          1. Get the request forwarder object through the request object: RequestDispatcher getRequestDispatcher(String path)
          2. Use the RequestDispatcher object for forwarding: RequestDispatcher forward(ServletRequest request,ServletResponse response)
        2. characteristic:
          1. The browser address bar path has not changed
          2. You can only access resources forwarded to the current server
          3. Forwarding is also a request
      3. Shared data:

        • Domain object: an object with scope that can share data within the scope
        • Request field: represents the scope of a request. It is generally used to share data among multiple resources requesting forwarding
        • method:
          1. setAttribute(String name,Object obj): stores data
          2. Getattribute (string name): get the value through the key
          3. void removeAttribute(String name): remove key value pairs through keys
      4. Get ServletContext:

        • ServletContext getServletContext()

Small case: user login

  • User login case requirements:

    1. Write login HTML login page
      1. Username & password two input boxes
    2. Use Druid database connection pool technology to operate the user table in mysql and day14 database
    3. Encapsulate JDBC using JDBC template technology
    4. Login succeeded, jump to the SuccessServlet display: login succeeded!
    5. Login failure, jump to FailServlet display: login failure, wrong user name or password
  • analysis

  • Development steps:

    1. Create project, import html page, configuration file, jar package

    2. Create database environment

      create database	day14;
      use day14;
      create table User(
      	id int primary key auto_increment not null,
      	username varchar(32),
      	pwd varchar(32)
      )
      
    3. Create package CN Domain, create User class

      package cn.domain;
      
      
      /**
       * User's entity class
       */
      public class User {
          private String id;
          private String username;
          private String password;
      
      
          public String getId() {
              return id;
          }
      
          public void setId(String id) {
              this.id = id;
          }
      
          public String getUsername() {
              return username;
          }
      
          public void setUsername(String username) {
              this.username = username;
          }
      
          public String getPassword() {
              return password;
          }
      
          public void setPassword(String password) {
              this.password = password;
          }
      
          @Override
          public String toString() {
              return "User{" +
                      "id='" + id + '\'' +
                      ", username='" + username + '\'' +
                      ", password='" + password + '\'' +
                      '}';
          }
      }
      
      
    4. Create package CN OP, create UserOp,

      package cn.util;
      
      import com.alibaba.druid.pool.DruidDataSourceFactory;
      
      import javax.sql.DataSource;
      import java.io.IOException;
      import java.io.InputStream;
      import java.sql.Connection;
      import java.sql.SQLException;
      import java.util.Properties;
      
      /**
       * JDBC The utility class uses the Durid connection pool
       */
      public class JDBCUtils {
          private static DataSource ds;
      
          static {
              try {
              //1. Load configuration file
              Properties pro = new Properties();
              //Use ClassLoader to load the configuration file and obtain the bytecode input stream
              InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druif.properties");
              pro.load(is);//Bytecode input
      
              //2. Initialize the connection pool object
                  ds = DruidDataSourceFactory.createDataSource(pro);
              } catch (IOException e) {
                  e.printStackTrace();
              } catch (Exception e) {
                  e.printStackTrace();
              }
      
      
          }
      
          /**
           * Get connection pool object
           */
          public   static DataSource getDataSource(){
              return ds;
          }
      
          /**
           * Get Connection object
           */
          public static Connection getConnectyion() throws SQLException {
              return ds.getConnection();
      
          }
      
      }
      
      
    5. Create package CN OP, create the class UserOp, and provide the login method

      package cn.op;
      
      
      import cn.domain.User;
      import cn.util.JDBCUtils;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.dao.DataAccessException;
      import org.springframework.jdbc.core.BeanPropertyRowMapper;
      import org.springframework.jdbc.core.JdbcTemplate;
      
      /**
       * Class that operates on the User table in the database
       */
      
      public class UserOp {
      
          //Declare the JDBC template object for sharing
          private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
          /**
           * Login method
           * @param loginUser Only user name and password
           * @return  Include all user data
           */
          public User login(User loginUser){
              try {
                  //1. Write sql
                  String sql = "select * from user where username = ? and pwd = ?;";
                  //2. Call query method
                  User user = template.queryForObject(sql,
                          new BeanPropertyRowMapper<User>(User.class),
                          loginUser.getUsername(), loginUser.getPwd());
      
                  return user;
              } catch (DataAccessException e) {
                  e.printStackTrace();//Log
              }
              return null;
          }
          
      
      
      }
      
    6. Write CN web. servlet. Loginservlet class

      package cn.myweb.servlet;
      
      import cn.domain.User;
      import cn.op.UserOp;
      
      
      import javax.servlet.ServletException;
      import javax.servlet.annotation.WebServlet;
      import javax.servlet.http.HttpServlet;
      import javax.servlet.http.HttpServletRequest;
      import javax.servlet.http.HttpServletResponse;
      import java.io.IOException;
      
      @WebServlet("/loginServlet")
      public class LoginServlet extends HttpServlet {
      
          @Override
          protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              try {
                  //1. Set code
                  req.setCharacterEncoding("utf-8");
                  //2. Get request parameters
                  String u = req.getParameter("username");
                  String p = req.getParameter("password");
                  //3. Encapsulate User objects
                  User logier = new User();
                  logier.setUsername(u);
                  logier.setPwd(p);
                  //Call the login method of UserOp
                  System.out.println(logier);
                  System.out.println("To enter");
                  UserOp op = new UserOp();
                  System.out.println("After entering");
                  User user = op.login(logier);
      
                  //5. Judgment
                  if(user==null){
                      //Login failed
                      req.getRequestDispatcher("/failServlet").forward(req,resp);
                  }else{
                      //Login succeeded
                      //Store data
                      req.setAttribute("user",user);
                      //Forward / redirect
                      req.getRequestDispatcher("/successServlet").forward(req,resp);
                  }
              } catch (ServletException | IOException e) {
                  e.printStackTrace();
              }
      
          }
      
          @Override
          protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
              this.doGet(req,resp);
          }
      }
      
      
    7. login. How to write the action path of form in HTML

      • Resource path of virtual directory + Servlet

      • <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <title>Sign in</title>
        </head>
        <body>
            <form action="/day14_2/loginServlet" method="post">
                <input type="text" name="username">
                <input type="password" name="pwd">
                <input type="submit" value="submit">
            </form>
        <!--    <a href="rd4">lianjie</a>-->
        </body>
        </html>
        
    8. BeanUtils tool class to complete data encapsulation

      • For encapsulating JavaBean s

        1. JavaBean s: standard java classes

          1. requirement:
            1. Class must be public decorated
            2. Constructor that must provide null arguments
            3. Member variables must be decorated with private
            4. Provide public setter and getter methods
          2. Function: encapsulate data
        2. Concept:

          • Member variables:
          • Property: the product intercepted by setter and getter methods
            • For example: getusername() -- > username -- > username
        3. method:

          1. setProperty()

          2. getProperty()

          3. populate(Object obj,Map map): encapsulates the key value pair information of the map set into the corresponding JavaBean object

            package cn.myweb.servlet;
            
            import cn.domain.User;
            import cn.op.UserOp;
            import com.mchange.v2.beans.BeansUtils;
            import com.mchange.v2.codegen.bean.BeangenUtils;
            import org.apache.commons.beanutils.BeanUtils;
            
            
            import javax.servlet.ServletException;
            import javax.servlet.annotation.WebServlet;
            import javax.servlet.http.HttpServlet;
            import javax.servlet.http.HttpServletRequest;
            import javax.servlet.http.HttpServletResponse;
            import java.io.IOException;
            import java.lang.reflect.InvocationTargetException;
            import java.util.Map;
            
            @WebServlet("/loginServlet")
            public class LoginServlet extends HttpServlet {
            
                @Override
                protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                    try {
                        //1. Set code
                        req.setCharacterEncoding("utf-8");
            //            //2. Get request parameters
            //            String u = req.getParameter("username");
            //            String p = req.getParameter("password");
            //            //3. Encapsulating User objects
            //            User logier = new User();
            //            logier.setUsername(u);
            //            logier.setPwd(p);
            
                        //2. Get all request parameters
                        Map<String, String[]> map = req.getParameterMap();
                        //3. Create User object
                        System.out.println("mima---"+map.get("password")[0]);;
                        User loginer = new User();
                        //3.2 using BeanUtils encapsulation
                        try {
                            BeanUtils.populate(loginer,map);//Remember to use Apache's, otherwise an error will be reported, and the data in the map will be encapsulated in the User
                        } catch (IllegalAccessException | InvocationTargetException e) {
                            e.printStackTrace();
                        }
                        //Call the login method of UserOp
                        System.out.println(loginer);
                        System.out.println("To enter");
                        UserOp op = new UserOp();
                        System.out.println("After entering");
                        User user = op.login(loginer);
            
                        //5. Judgment
                        if(user==null){
                            //Login failed
                            req.getRequestDispatcher("/failServlet").forward(req,resp);
                        }else{
                            //Login succeeded
                            //Store data
                            req.setAttribute("user",user);
                            //Forward / redirect
                            req.getRequestDispatcher("/successServlet").forward(req,resp);
                        }
                    } catch (ServletException | IOException e) {
                        e.printStackTrace();
                    }
            
                }
            
                @Override
                protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                    this.doGet(req,resp);
                }
            }
            
            

("user",user);
//Forward / redirect
req.getRequestDispatcher("/successServlet").forward(req,resp);
}
} catch (ServletException | IOException e) {
e.printStackTrace();
}

             }
         
             @Override
             protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                 this.doGet(req,resp);
             }
         }
         
         ```

Keywords: Java Web Development network Network Protocol http

Added by zarathu on Thu, 23 Dec 2021 14:20:52 +0200