Request Object Overview

Direction: Browser -> Server

Responsible for obtaining client request data

The Request object is a request from the client to the server, including information submitted by the user and some information about the client. The client submits data through an HTML form or by providing parameters after the web page address, and the server retrieves the data through the relevant methods of the Request object.

  • Looking at the service method in the Servlet, we can see that the ServletRequest interface is used in the Servlet, and we are using the ServletRequest subinterface HttpServletRequest, which inherits from the ServletRequest. Is a Request object related to the HTTP protocol
  • The subinterface we use, HttpServletRequest, is provided by the Tomcat engine
  • Can realize the client to the server to send a request, request content includes: request line, request header, request body

The HTTP request

The Request object gets the Request row

  • API
methods The return value describe
getMethod() String How to GET the submission (GET,POST)
getRequestURI() String Gets the parameters of the request, request server path
getRequestURL() StringBuffer Gets the parameters of the request, request server path
getQueryString() String GET the argument after the question mark on the request line (GET)
getContextPath() String Gets the WEB application name
  • Code demo
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // The request object method getMethod() gets the request method of the client
    String method = request.getMethod();
    System.out.println(method);
    // The method String getRequestURI() gets the request server path
    // the StringBuffer getRequestURL() method gets the request server path
    String URI = request.getRequestURI();
    StringBuffer URL = request.getRequestURL();
    System.out.println("URI=="+URI);// /web04/line
    System.out.println("URL=="+URL);// http://localhost:8080/web04/line

    // The String getQueryString() method gets the request row,? All the following parameters
    String query = request.getQueryString();
    System.out.println(query);//user=tom&pass=123&

    String getContextPath()
    String path = request.getContextPath();
    System.out.println(path);// /web04
    // Get the name of the WEB application and use it with redirection
    //response.sendRedirect(request.getContextPath()+"/ddd");
}
Copy the code

The Request object gets the Request header

Request header data format key-value pairs, k: V

Instructional information, directs the server

methods The return value describe
getHeader(String name) String Get a request header for a key corresponding to a value
getHeaderNames() Enumeration Gets the keys of all request headers
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    /* * Enumeration getHeaderNames() Retrieves all request header keys * return value Enumeration interface (vector Enumeration) * Set :1.0-1.1 Enumeration set 1.2 iterators * Iterator: hasNext() next() * Enumeration: hasMoreElement() nextElement() */
    Enumeration<String> enums  = request.getHeaderNames();
    while (enums.hasMoreElements()){
         key = enums.nextElement();
         String value = request.getHeader(key);
        System.out.println(key+"= ="+value); }}Copy the code

Request Obtains Request parameters

methods The return value describe
GetParameter (Name value in the form) String Get submitted parameters (one name for one value)
GetParameterValues (Name value in the form) String[] Get submitted parameters (one name for multiple values)
getParameterMap() Map<String,String[]> Get the submitted parameters and store the submitted parameter names and corresponding values into a Map collection
<body>
    <form action="/web02/param" method="post">User name:<input type="text" name="username"><br/>Password:<input type="password" name="password"><br/>Hobbies:<input type="checkbox" name="hobby" value="Basketball">basketball<input type="checkbox" name="hobby" value="football">football<input type="checkbox" name="hobby" value="pingpang">PingPing ball<br/>
        <input type="submit">
    </form>
</body>
Copy the code
@WebServlet(urlPatterns = "/param")
public class ParamServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Get the submitted parameters (one name corresponds to one value)
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username +"= =" +password);
        // Get the submitted parameters (one name corresponds to multiple values)
        String[] hobbies = request.getParameterValues("hobby");
        System.out.println("hobbies = " + Arrays.toString(hobbies));
        // Get the submitted parameters and store the submitted parameter names and corresponding values into a Map collection
        Map<String, String[]> map = request.getParameterMap();
        for(String key : map.keySet()){
            String[] values = map.get(key);
            System.out.println(key + "= ="+ Arrays.toString(values)); }}Copy the code

The Request object receives Chinese garble processing for form Request parameters

Chinese is received in POST mode

  • Causes of garbled characters:

    • The data submitted by POST is in the request body. After receiving the data, the request object puts the data into the request buffer. The buffer has encoding (default ISO-8859-1: Chinese is not supported).
  • Solution:

    • Change the encoding of the request buffer.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Change the encoding of the request buffer
    request.setCharacterEncoding("utf-8");

    // Get the request parameters
    String user = request.getParameter("user");
    System.out.println("user = " + user);
}
Copy the code

Receive Chinese in GET mode

After Tomcat8.5, Tomcat automatically handles Chinese garbled characters in GET requests

However, in versions prior to Tomcat8.5, Chinese garbled characters in get requests need to be handled by themselves

  • Causes of garbled characters:

    • Get submits data after the URL of the request line, in the address bar actually has been a URL encoding.
  • Solution:

    • The value stored in the request buffer is retrieved isO-8859-1 and decoded utF-8.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    /* Tomcat automatically handles the garble in the request line after Tomcat8.5 However, in previous Versions of Tomcat, Chinese garbled characters in GET requests need to be handled by themselves. The values stored in the request buffer are obtained in ISO-8859-1 and decoded in UTF-8 mode. * /
    String user = request.getParameter("username"); //

    // Get the value stored in the request buffer isO-8859-1
    byte[] bytes = user.getBytes("iso-8859-1");
    // Decode in UTF-8 mode
    String value = new String(bytes, "utf-8");

    System.out.println("user = " + user);
}
Copy the code

BeanUtils encapsulates the data in a map into a POJO class

Guide package

Pojo class

package cn.itcast.pojo;

import java.util.Arrays;

public class User {
    private String username;
    private String password;
    private String[] hobby;

    public String getUsername(a) {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword(a) {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String[] getHobby() {
        return hobby;
    }

    public void setHobby(String[] hobby) {
        this.hobby = hobby;
    }

    @Override
    public String toString(a) {
        return "User{" +
                "username='" + username + '\' ' +
                ", password='" + password + '\' ' +
                ", hobby=" + Arrays.toString(hobby) +
                '} '; }}Copy the code

page

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/web0202/demo15" method="post">User name:<input type="text" name="username"><br/>Password:<input type="password" name="password"><br/>Hobbies:<input type="checkbox" name="hobby" value="Basketball">basketball<input type="checkbox" name="hobby" value="football">football<input type="checkbox" name="hobby" value="pingpang">PingPing ball<br/>
    <input type="submit">
</form>
</body>
</html>
Copy the code

servlet

package cn.itcast.web;

import cn.itcast.pojo.User;
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("/demo15")
public class ServletDemo15 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Resolve the problem of garbled Chinese characters in data sent by the server to the browser
        response.setContentType("text/html; charset=utf-8");
        request.setCharacterEncoding("utf-8");

        Map<String, String[]> parameterMap = request.getParameterMap();
        User user = new User();
        try {
            BeanUtils.populate(user, parameterMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(user);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); }}Copy the code

The principle of

The map key is used to call the name of the set method, and the reflection technique is used to call the set method, passing in the value

Request a domain object

Request as an API for domain objects

Request is scoped as domain object

The Request object is simply an encapsulation of a Request message sent from the client browser to the server. The data validity period stored in the Request is essentially a Request scope.

One-time request scope: A request is sent from the client browser to the server, and the server responds to the browser for this request. When the server responds, the request object is destroyed and the data stored in it is invalid.

If there are two requests, the two request objects are not the same, so the contents of one are not accessible to the other. But if there is a single request, and the request is still a request object after the server forwards it, then the stored objects in both of them can be accessed

Each request creates a new request object, which is destroyed immediately after the response is complete.

  • API
methods The return value describe
setAttribute(String name, Object obj) void Save data to the Request field
getAttribute(String name) Object Get data from the Request field
removeAttribute(String name) void Remove data from the Request field
  • Code demo

servlet1

@WebServlet(urlPatterns = "/my1")
public class MyServlet1 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Store values to the Request field object
        request.setAttribute("language"."java");
        // Take the value from the request domain object
        Object value = request.getAttribute("language");
        System.out.println("MyServlet1 value = " + value);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}Copy the code

servlet2

@WebServlet(urlPatterns = "/my2")
public class MyServlet2 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Take the value from the request domain object
        Object value = request.getAttribute("language");
        System.out.println("MyServlet2 value = " + value);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}Copy the code

Forward requests

Request forwarding

The RequestDispatcher object is obtained from the ServletRequest object

methods The return value describe
getRequestDispatcher(String path) 请求转发;分派请求 Get the RequestDispatcher object

The request is then forwarded according to the methods in the RequestDispatcher

methods The return value describe
forward(ServletRequest request, ServletResponse response) void Request forwarding

The implementation steps of forwarding

  • RequestDispatcher getRequestDispatcher is the forwarder returned by the request object method
  • Use the forwarder object method forward

Code implementation

servlet1

@WebServlet(urlPatterns = "/my1")
public class MyServlet1 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Store values to the Request field object
        request.setAttribute("language"."java");
        // Take the value from the request domain object
        Object value = request.getAttribute("language");
        System.out.println("MyServlet1 value = " + value);

        // Forward the request
        request.getRequestDispatcher("/my2").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}Copy the code

servlet2

@WebServlet(urlPatterns = "/my2")
public class MyServlet2 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Take the value from the request domain object
        Object value = request.getAttribute("language");
        System.out.println("MyServlet2 value = " + value);

        // Respond back to the browser
        response.setContentType("text/html; charset=utf-8");
        response.getWriter().print("I am MyServlet2 page data");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}Copy the code

9 Difference between request forwarding and redirection

  • Request forwarding is one request and one response, whereas redirection is two requests and two responses.
  • The request forwarding address bar does not change, but the redirection address bar does.
  • The request forwarding path does not contain a project name, but redirection requires a project name path.
  • Requests are forwarded only within this site and redirects can be directed to any site.

9.2 Code Demonstration

MyServlet1

@WebServlet(urlPatterns = "/my1")
public class MyServlet1 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Store values to the Request field object
        request.setAttribute("language"."java");
        // Take the value from the request domain object
        Object value = request.getAttribute("language");
        System.out.println("MyServlet1 value = " + value);

        // Forward the request
        //request.getRequestDispatcher("/my2").forward(request, response);
        // Redirect
        response.sendRedirect("/web02/my2");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}Copy the code

MyServlet2

@WebServlet(urlPatterns = "/my2")
public class MyServlet2 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Take the value from the request domain object
        Object value = request.getAttribute("language");
        System.out.println("MyServlet2 value = " + value);

        // Respond back to the browser
        response.setContentType("text/html; charset=utf-8");
        response.getWriter().print("I am MyServlet2 page data");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }}Copy the code
  • Note:

    • If you need to use Request for value transfer, you need to use request forwarding.
    • Redirects must be used if a page needs to be redirected to another site, instead of using Request for value passing.

Client and server address writing method

  • What is a client address: the address where the client accesses the server directly is the client address

    • The name of the Web application must be added to the address for accessing the Web application from the client
  • What is a server-side address: an address accessed within a Web application is a server-side address

    • Feature: No need to write the web application name when accessing
  • When writing an address, how to distinguish whether to add the name of the Web application

    • Depending on whether it’s in or out of the Web application

      • Client address

        • Directly write the URL address – client address in the address bar
        • The href – client address of the tag
        • The action—– client address of the form
        • Location. href —- Client address
        • Response Redirection of the response object sendRedirect(address) —– Client address
      • Now remember one server address:

        • Request getRequestDispatcher(forward address) – server address
        • The mapping path of the servlet – also the server address