@[TOC]

2 Request Object

2.1 Overview of request Objects

2.1.1 About Requests

A request, by definition, is that the user wants to get some resources from the server and make inquiries to the server. In the B/S architecture, the client browser issues a query to the server. In our JavaEE project, the client browser issues queries that comply with the HTTP protocol.

The request object is the object used to send the request in JavaEE project. Our common objects are ServletRequest and HttpServletRequest, and the difference is whether or not they are related to the HTTP protocol.

2.1.2 Common Request Objects

2.2 Common methods

Website:Javaee. Making. IO/javaee – spec… We explain it in Chinese as shown below:

2.3 Example of using request Objects

2.3.1 Common methods for requesting objects 1- Obtaining various paths

/** * Request the object to obtain various information */
public class RequestDemo1 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // Local address: server address
        String localAddr = request.getLocalAddr();
        // Local name: server name
        String localName = request.getLocalName();
        // Local port: server port
        int localPort = request.getLocalPort();
        // Client IP address
        String remoteAddr = request.getRemoteAddr();
        // Call the host
        String remoteHost = request.getRemoteHost();
        // Visitor port
        int remotePort = request.getRemotePort();
        // Uniform Resource Identifier
        String URI = request.getRequestURI();
        // Uniform resource locator
        String URL = request.getRequestURL().toString();
        // Get the query string
        String queryString = request.getQueryString();
        // Get the Servlet mapping path
        String servletPath = request.getServletPath();

        // Output the content
		System.out.println("getLocalAddr() is :"+localAddr);
		System.out.println("getLocalName() is :"+localName);
		System.out.println("getLocalPort() is :"+localPort);
		System.out.println("getRemoteAddr() is :"+remoteAddr);
		System.out.println("getRemoteHost() is :"+remoteHost);
		System.out.println("getRemotePort() is :"+remotePort);
		System.out.println("getRequestURI() is :"+URI);
		System.out.println("getRequestURL() is :"+URL);
        System.out.println("getQueryString() is :"+queryString);
        System.out.println("getServletPath() is :"+servletPath);
    }

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

Running results:

2.3.2 Request Object Common Method 2- Obtain request header information

/** * get the request header *@authorDark horse programmer *@Company http://www.itheima.com
 */
public class RequestDemo2 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1. Get the header value by name
        String value = request.getHeader("Accept-Encoding");
        System.out.println("getHeader():"+value);

        //2. Get the value of the header by name
        Enumeration<String> values = request.getHeaders("Accept");
        while(values.hasMoreElements()){
            System.out.println("getHeaders():"+values.nextElement());
        }

        //3. Get an enumeration of the names of the request headers
        Enumeration<String> names = request.getHeaderNames();
        while(names.hasMoreElements()){
            String name = names.nextElement();
            String value1 = request.getHeader(name);
            System.out.println(name+":"+value1); }}public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException { doGet(request, response); }}Copy the code

The result is shown below

2.3.3 Common Methods for Request Objects 3- Get request parameters (very important)

The content is more, please remove drive another blog: yangyongli.blog.csdn.net/article/det…

2.3.4 Read request information in stream form

In addition to obtaining the request parameters as described in section 2.3.3, we can also obtain them in the following code:

/** * Read the request body as a stream */
public class RequestDemo4 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1. Get the byte input stream of the request body
        ServletInputStream sis = request.getInputStream();
        //2. Read the data in the stream
        int len = 0;
        byte[] by = new byte[1024];
        while((len = sis.read(by)) ! = -1){
            System.out.println(new String(by,0,len)); }}public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException { doGet(request, response); }}Copy the code

2.3.5 Chinese Encoding Problem in the Request Body

Too much content, please remove drive another blog: yangyongli.blog.csdn.net/article/det…

2.3.6 Request Forwarding (Difference with Redirection)

In real development, redirection and request forwarding are both responses we use, so what’s the difference between them? Let’s look at the following example:

/ redirection features: * * * * two requests, the browser behavior, change the address bar, request scope of data will be lost * forward requests: * a request, the server, the address bar, the request data is not lost in the domain of * * request domain scope: * the current request (request), and the current request forward *@authorDark horse programmer *@Company http://www.itheima.com
 */
public class RequestDemo6 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1. Get the request scheduling object
        RequestDispatcher rd = request.getRequestDispatcher("/RequestDemo7");// If it is for the browser to read, / can write without writing. If you are showing the server, in general, / is required.
        // Put the data into the request field
        request.setAttribute("CityCode"."bj-010");
        //2. Implement the actual forwarding operation
        rd.forward(request, response);// Implement the actual forward operation
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException { doGet(request, response); }}Copy the code
/** * the forwarding destination *@authorDark horse programmer *@Company http://www.itheima.com
 */
public class RequestDemo7 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Get the data in the request field
        String value = (String)request.getAttribute("CityCode");
        response.getWriter().write("welcome to request demo 7 "+value);
    }

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

2.3.7 Request Contains

In actual development, we may need to combine the contents of two servlets together to respond to the browser, and you all know that HTTP protocol is characterized by one request, one response.

== So it is absolutely impossible to have two servlets responding at the same time. = =

Then we need to use the request contain to combine the output of the responses from both servlets. Let’s look at a specific use example:

/** * the request contains ** which combines the output of the responses from both servlets. * Note: * This inclusion is a dynamic inclusion. * * Dynamic inclusion features: * compile separately, only merge the output at the end. * /
public class RequestDemo8 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().write("I am request demo8 ");
        //1. Get the request scheduling object
        RequestDispatcher rd = request.getRequestDispatcher("/RequestDemo9");
        //2. Implement the included operation
        rd.include(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException { doGet(request, response); }}Copy the code
/** ** included */
public class RequestDemo9 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().write("include request demo 9 ");
    }

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

2.3.8 More details

Note the following when requesting forwarding: == The Servlet responsible for forwarding, the response body before and after forwarding is lost, and the forwarding destination responds to the browser. = =

Note for request inclusion: == The included’s response header is missing. Because it’s included. = =