Learning notes of Request (belonging to Servlet learning course)

Posted by crimsonmoon on Mon, 07 Mar 2022 03:05:30 +0100


When the browser accesses the server, it will encapsulate the parameter data, protocol version and request header information submitted by the user into a request message (i.e. request packet) and send it to the server.
The Request message received by the server (such as Tomcat) will be encapsulated in the Request object. Programmers can get the Request message data through the Request object.

Get request message data

1. Get the data of the request line

GET /web-demo-03/demo01?name=zhangsan HTTP/1.1

method:
1.1. GET request method: GET
String getMethod()

1.2. Get virtual directory: / web-demo-03
String getContextPath()

1.3. Get Servlet path: / demo01
String getServletPath()

1.4. Get request URI: / web-demo-03/demo01
URI uniform resource identifier
String getRequestURI()

1.5. GET request parameters of GET method: name=zhangsan
String getQueryString()

1.6. Get request URL: http://localhost:8080/web-demo-03/demo01
URL uniform resource locator
String getRequestURL()

1.7. Obtain protocol and version: http/1.1
String getProtocol()

1.8. Get the IP address of the client
String getRemoteAddr()

2. Get the data of the request header

Request header names are not case sensitive.

method:
String getHeader(String name) gets the value of the request header through the name of the request header
Enumeration < string > getheadernames() gets all request header names. Enumeration is similar to iterators

Example code:

package priv.lwx.javaex.web_demo_03.web.servlet;
 /**
 * Get referer to prevent chain theft
 *
 * @author liaowenxiong
 * @date 2021/12/29 11:21
 */


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(value = "/demo06")
public class ServletDemo06 extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Get referer
    String referer = request.getHeader("referer");
    System.out.println(referer);
    // Prevent chain theft
    if (referer != null) {
      if (referer.contains("/web-demo-03")) {
        // Normal access in application
        System.out.println("Play a movie");
      } else {
        // Out of application access
        System.out.println("Want to see a movie? Come on, Youku!");
      }
    }

  }
}

3. Obtain the data of the requestor

Only the post request method has a request body, which encapsulates the request parameters of the post request.

Steps:
3.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 all types of data (mainly used for file upload, video upload and other scenes)

3.2. Fetch data from stream object

Example code:

package priv.lwx.javaex.web_demo_03.web.servlet.request;

/**
 * Get the data of the request body
 *
 * @author liaowenxiong
 * @date 2021/12/29 11:21
 */


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(value = "/request-demo05")
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 the data of the request message body
    // 1. Get character stream
    BufferedReader reader = request.getReader();
    // 2. Read data
    String line = null;
    while ((line = reader.readLine()) != null) {
      System.out.println(line);
    }
  }
}

4. Obtain other data

4.1. General way to get request parameters

Regardless of the get or post mode, you can use the following method to obtain the request parameters.

method:
String getParameter(String name): get the value of the parameter according to the parameter name
String[] getParameterValues(String name): an array of parameter values obtained by parameter name. For example: Hobby = DS & Hobby = PS
Enumeration getParameterNames(): get the names of all request parameters

 Enumeration<String> parameterNames = req.getParameterNames();
// Iterate through the Enumeration object
while (parameterNames.hasMoreElements()) {
	String s = parameterNames.nextElement();
	System.out.println(s);
}

Map < string, string [] > getparametermap(): get the map collection of all request parameters

Chinese garbled code problem

tomcat 8 has solved the problem of Chinese garbled code in get request mode, but there will be Chinese garbled code in post request mode.

terms of settlement:
Before obtaining the parameters, set the decoded character encoding to utf-8, and the code is as follows:

request.setCharacterEncoding("utf-8");

This character code should be consistent with the character code of the front page.

4.2. Request forwarding

Request forwarding: a resource jump mode inside the server

Steps:
4.2.1. Obtain the request forwarder object through the request object: RequestDispatcher getRequestDispatcher(String path). Path is the resource path of the forwarding target

4.2.2. Use the RequestDispatcher object to forward: RequestDispatcher forward(ServletRequest request, ServletResponse response)

characteristic:
4.2.3. The access path of the browser address bar has not changed
4.2.4. It can only be forwarded to resources inside the current server
4.2.5. Forwarding is just a request

4.3. shared data

Domain object: an object with scope, which can share data within the scope
Request domain object: represents the scope of a request. It is generally used to share data among multiple resources for request forwarding

method:
void setAttribute(String name,Object obj): stores data
Object getAttribute(String name): get data; Get property value by property name
void removeAttribute(String name): delete data; Delete the corresponding data through the attribute name; Remove the corresponding key value pair through the key

4.4. Get ServletContext object

ServletContext getServletContext()

Inheritance and implementation system

The HttpServletRequest interface inherits from the ServletRequest interface

org.apache.catalina.connector.RequestFacade (the type implemented by tomcat) implements the HttpServletRequest interface

Topics: Java servlet request