Http Protocol Overview

HTTP is the hypertext transfer protocol. Is the data format specification for client and server interactions. There are HTTP requests and HTTP responses.

  • When a browser requests a Web resource from the server, it is said that the browser sends an HTTP request to the server.
  • An HTTP response represents the server sending back data to the browser.

Simply put: Request: data sent by the client to the server; Response: data sent by the server to the client.

Requests and responses are divided into rows, headers, and bodies. There is a request after a response, no request, no response.

HttpServletRequest

An overview of the

The HttpServletRequest object represents the client’s request. When the client accesses the server through HTTP, all the information in the HTTP request header is encapsulated in this object. The developer can obtain the client’s information through the method of this object.

Request is an object that encapsulates the request text. Therefore, all contents in the request text can be obtained through request, including the request header, request body and request line

An example request:

Request line, request header, request body

The request line

  • Basic information about this request
  • Format: Request Mode Request resource protocol version
  • For example,POST/day29 demo01 HTTP / 1.1

Request header

  • Additional information about this request
  • Format: one keyvalue pair in a row. One keyvalue pair is a request header. A request can have multiple headers
  • Such as:Referer:http://localhost:8080/day29/_01http.html
  • Related methods:
    • String getHeader(String name) Gets the header value based on the header name
    • Long getDateHeader(java.lang.string name) gets the specified header content Date
    • Int getIntHeader(java.lang.string name) gets the specified header content int
    • Enumeration getHeaderNames() gets all header names
    • Enumeration getHeaders(String name) Obtains the same header information based on the header name

Code examples:

Enumeration<String> headerNames = req.getHeaderNames();
        while(headerNames.hasMoreElements()){
            String key = (String)headerNames.nextElement();
            String value = req.getHeader(key);
            System.out.println(key+"="+value);
        } 
Copy the code

Request body

  • The body data of this request is the submitted form parameters
  • Format: Form data submission format Name = Value&Name =value&…
  • Such as:username=lisi
  • Note: Only for POST submission, there must be a form item with the name attribute, and then there will be data in the request body. Otherwise, there is no request body
  • Methods related to form fetching:
    • String getParameter(name) : Gets the value method of the value attribute based on the name of the name attribute in the form
    • String[] getParameterValues (String Name) : Method provided specifically for checkbox fetching
    • GetParameterNames () : Method to get all the names of the submitted form
    • Map

      getParameterMap() : getParameterMap() : getParameterMap()
      ,>
    • GetInputStream: Gets all form data as a byte stream
  • Methods related to manipulating non-form data (Request is also a domain object) :
    • void setAttribute(String name, Object value);
    • Object getAttribute(String name);
    • Void removeAttribute(String name);
  • Methods related to request forwarding:
    • RequestDispatcher getRequestDispatcher(String path) // Get the assistance object that the request is forwarded or included in
    • Forward (ServletRequest Request, ServletResponse Response) // The method of forwarding
    • Include (ServletRequest Request, ServletResponse Response) // Request includes
  • Encoding related methods:
    • Resolves post encoding
      • Request. SetCharacterEncoding (” utf-8 “) : tell the server what the client code, the only way to handle a post request
    • Solve get encoding
      • String name = new String(name.getBytes(” ISO-8859-1 “), “UTF-8”);

Added: Other common request methods

  • getMethod();
  • getRequestURL();
  • getRequestURI();
  • getServerName();
  • getServerPort();
  • getContextPath();
  • getServletPath();
  • getQueryString();
  • getRemoteAddr();
  • getProtocol();

Example:

@Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1. Uniform Resource Tag /Web_Servlet/ServletTest3 String URI = req.getrequestURI (); System.out.println(uri); / / 2. The uniform resource locator http://localhost:6060/Web_Servlet/ServletTest3 StringBuffer url = the req. GetRequestURL (); System.out.println(url); HTTP/1.1 String potocol = req.getProtocol(); System.out.println(potocol); HTTP String scheme = req.getScheme(); System.out.println(scheme); String serverName = req.getServername (); String serverName = req.getServername (); System.out.println(serverName); //6. Port 6060(this is my modified port, default is 8080) int port = req.getServerPort (); System.out.println(port); Web_Servlet String contextPath = req.getContextPath(); System.out.println(contextPath); Servlet path /ServletTest3 String servletPath = req.getServletPath(); System.out.println(servletPath); //9. Get all request parameters, i.e.? Everything after that. username=faker&password=mid String queryString = req.getQueryString(); System.out.println(queryString); //10. Remote host IP address 0:0:0:0:0:0:0:1 String remoteAddr = req.getremoteAddr (); System.out.println(remoteAddr); }Copy the code

Summarize some common methods

  • Gets the data for the requested row

    • Get request mode data
      • Syntax :Request object.getMethod ():
      • Method returns the corresponding request type string (the common request type get/ POST)
      • Generally, the default request is get, and a POST request is made only when post is specified.
    • Gets the project path in the request line
      • Syntax: Request object.getContextPath ();
      • Method returns the corresponding project path string
    • Obtain the client IP address
      • Syntax: Request object.getremoteaddr ();
      • Method returns the IP address to access the customer
  • Gets the data for the request header

    • Gets the value of the specified request header
      • Syntax: Request. GetHeader (key)
      • In the request header, data is stored as key-value pairs, keys are passed in, and values are retrieved
    • Gets the values of all request headers
      • Grammar: Request. GetHeaderNames ()
      • Returns the values of all request headers in the form of an enumerated object.
  • Gets the data for the request body

    • Get single-valued parameters:String Value = Request. getParameter(Name attribute of tag body)
    • Get multi-valued parameters:String [] values = request. GetParametreValues (the name attribute of the tag body)
    • Get all parameters:Map<String, String[]> map = request.getParameterMap()

Garbled characters appear in fetching form data

There will be no garbled characters in Get mode, because Tomcat version 8 and above has been solved for us.

The Post mode will have the problem of garbled characters: all the garbled characters are due to the different decoding and encoding methods

  • Request is decoded with the ISO-8859 character set by default, whereas our pages are encoded with the UTF-8 character set
  • Solution: modify the decoding method, grammar: Request. SetCharacterEncoding (” utf-8 “)
  • Note: This must be done before the parameters are received

Understanding of the Request domain object

Request is a domain object, provided by the Servlet specification, that can access data and share data in its scope.

Differences between objects in different domains: Different scopes

Domain objects access data by:

  • SetAttribute (String name, Object value)
  • Get data: getAttribute(String name)
  • Delete data: removeAttribute(String name)

The scope of the request domain object:

  • When created: A request starts
  • When to destroy: A request ends
  • Scope: The duration of a request

Request Underlying schematic diagram

HttpServletResponse

An overview of the

The Web server receives the HTTP request from the client and creates a Request object representing the request and a Response object representing the response for each request. Request and Response objects stand for request and response, so to get the data submitted by the client, we just need to look for the Request object. To output data to the container, just look for the Response object. The HttpServletResponse object represents the server’s response. This object encapsulates methods for sending data, response headers, and response status codes to the client.

First look at an overview of the picture to build an impression of Response

Response Response data

As shown in the figure above, we can quickly find several key terms of response, such as response header, response body, status code, etc

During an access we can see the response information as shown in the following figure:

The data in the response line indicates that the HTTP protocol version is HTTP/1.1 and the status code is 200. The description of the status code is OK.

About the response status code

Response status code: the server tells the client (browser) the status of the request and response

The status codes are all three digits

  • 1XX: The server receives the message from the client but does not receive the message. After waiting for a period of time, the server sends the 1XXX status code
  • 2xx: success, representative: 200
  • 3xx: Redirection, representing: 302 (redirection) 304 (Access cache)
  • 4xx: client error, representing 404 (unresponsive resource in request path) 405 (request mode does not correspond with processing method)
  • 5XX: server error, representing 500 (server internal error)

Data in the response header

  • Content-type: text/ HTML — Indicates the data Type
  • Content-length: 137 — Indicates the data Length
  • Date: Sun, 01 Mar 2020 10:19:50 GMT

You can view the information about the response header corresponding to the image above.

Response workflow

Relevant methods

  • SetStatus (int SC) Sets the response status code
  • SetHeader (String name, String Value) Sets the response header information
  • getWrite(); Character output stream
  • getOutputStream(); Byte output stream
  • SetCharacterEncoding (String Charset) Tells the server what encoding to use
  • SetContentType (String type) tells the content type of the response (text/ HTML, application/json, etc.)

Aside 1: Two setCharacterEncoding

Request. SetCharacterEncoding () after the specified by the getParameter (), direct access to the correct string, if not specified, the default use iso8859-1 encoding. It is worth noting that no getParameter() can be executed before setCharacterEncoding() is executed. Furthermore, this specification is valid only for the POST method, not the GET method. When the first getParameter() is executed, Java will analyze all submissions as encoded, and the subsequent getParameter() will not be analyzed, so setCharacterEncoding() is invalid. SetCharacterEncoding () will not work if the content is in the URL and has already been analyzedfrom the beginning.

The HTTP response. SetCharacterEncoding Settings Response codes, if use the response before setContentType set the encoding format, use the response. The setCharacterEncoding cover before setting the specified encoding format. As with Response. setContentType, this method must be called before getWriter executes or the response is submitted

Request and Response often involve redirection and forwarding, which will be covered in the next topic.