Servlet--HttpServletRequest to obtain the detailed explanation of request information (request header, request line and parameters)

Posted by Sassy34 on Fri, 17 Dec 2021 04:56:54 +0100

Overview of ttpServletRequest object
In the Servlet API, an HttpServletRequest interface is defined, which inherits from the ServletReauest interface and is specially used to encapsulate HTTP request messages. Since the HTTP request message is divided into three parts: request line, request header and request message body, the relevant methods to obtain the request line, request header and request message body are defined in the HttpServletRequest interface.
When creating a Servlet, we will override the service() method or doGet()/doPost(). These methods have two parameters, one is the request representing the request and the other is the response representing the response.
The type of request in the service method is ServletRequest, while the type of request in the doGet/doPost method is HttpServletRequest. HttpServletRequest is a sub interface of ServletRequest. Its functions and methods are more powerful. Today we learn HttpServletRequest.
Operation process of request

Grab HTTP requests through the packet capture tool

Obtain request line information through request
When accessing a Servlet, the request line of the request message contains information such as the request method, request resource name, request path, etc. in order to obtain these information, a series of methods for obtaining the request line are defined in the HTTPServletRequest interface, as shown in the following table:

Method declarationFunction description
String getmethod()This method is used to obtain the request method (such as GET, POST, etc.) in the HTTP request message
String getReauestURI()This method is used to obtain the resource name part in the request line, that is, the part after the host and port of the URL and before the parameter part
String getQueryString()This method is used to obtain the parameter part in the request line, that is, all contents after the question mark after the resource path
String getProtocol()This method is used to obtain the protocol name and version in the request line, for example, HTTP/1.0 or HTTP/1.1
String getContextPath( )This method is used to obtain the path belonging to the web application in the request URL. This path starts with "/", indicating that relative to the root directory of the whole web site, the end of the path does not contain "/. If the request URL belongs to the root directory of the web site, the returned result is an empty string ''
String getServletPath()This method is used to obtain the name of the Servlet or the path mapped by the Servlet
String getRemoteAddr( )This method is used to obtain the IP address of the requesting client. Its format is similar to "192.168.0.1"
String getRemoteHost()This method is used to obtain the complete host name of the requesting client. Its format is similar to "pc1.xxxx.cn". It should be noted that if there is no
int getRemotePort()This method is used to obtain the port number of the requesting client network connection
String getLocalAddr()This method is used to obtain the IP address on the Web server that receives the current requested network connection
String getLocalName()This method is used to obtain the host name corresponding to the current network connection IP received on the Web server
int getLocalPort()This method is used to obtain the port number on the Web server to receive the current network connection
String getServerName()This method is used to obtain the HOST name pointed to by the current request, that is, the HOST name part corresponding to the HOST header field in the HTTP request message
int getServerPort()This method is used to obtain the port number of the server to which the current request is connected, that is, the port number corresponding to the HOST header field in the HTTP request message
String getScheme()This method is used to obtain the requested protocol name, such as http, https or ftp
StringBuffer getRequestURL()This method is used to obtain the complete URL when the client sends a request, including protocol, server name, port number, resource path and other information, but does not include the following query parameters. Note that the getRequestRUL() method returns a String buffer type instead of a String type.

Example:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //Get information about the request line
        out.println("getMethod:" + request.getMethod() + "<br/>");
        out.println("getQueryString:" + request.getQueryString() + "<br/>");
        out.println("getProtocol:" + request.getProtocol() + "<br/>");
        out.println("getContextPath" + request.getContextPath() + "<br/>");
        out.println("getPathInfo:" + request.getPathInfo() + "<br/>");
        out.println("getPathTranslated:" + request.getPathTranslated() + "<br/>");
        out.println("getServletPath:" + request.getServletPath() + "<br/>");
        out.println("getRemoteAddr:" + request.getRemoteAddr() + "<br/>");
        out.println("getRemoteHost:" + request.getRemoteHost() + "<br/>");
        out.println("getRemotePort:" + request.getRemotePort() + "<br/>");
        out.println("getLocalAddr:" + request.getLocalAddr() + "<br/>");
        out.println("getLocalName:" + request.getLocalName() + "<br/>");
        out.println("getLocalPort:" + request.getLocalPort() + "<br/>");
        out.println("getServerName:" + request.getServerName() + "<br/>");
        out.println("getServerPort:" + request.getServerPort() + "<br/>");
        out.println("getScheme:" + request.getScheme() + "<br/>");
        out.println("getRequestURL:" + request.getRequestURL() + "<br/>");
    }

Accessed through the browser, the page displays:

Get the request header through request
When requesting a Servlet, you need to pass additional information to the server through the request header, such as the data type, compression mode, language, etc. that the client can receive. To this end, a series of methods for obtaining HTTP request header fields are defined in the HttpServletRequest interface, as shown in the following table:

Method declarationFunction description
String getHeader(String name)This method is used to obtain the value of a specified header field. If the request message does not contain the specified header field, the getHeader() method returns null; If the request message contains more than one header field with the specified name, the getHeader() method returns the value of the first header field
Enumeration getHeaders(String name)This method returns an Enumeration collection object, which consists of all header field values of a specified name appearing in the request message. In most cases, a header field name appears only once in the request message, but sometimes it may appear multiple times
Enumeration getheaderNames()This method is used to get an Enumeration object that contains all the request header fields
int getIntHeader(String name)This method gets the header field of the specified name and converts its value to type int. Note that if the header field of the specified name does not exist, the return value is - 1; If the value of the obtained header field cannot be converted to int type, a NumberFormatException exception will occur
Long getDateHeader(String name)This method is used to obtain the value of the specified header field and convert it into a long integer representing date / time in GMT time format. This long integer is the time value in milliseconds calculated from 0:0:0 on January 1, 1970
String getContentType()This method is used to obtain the value of the content type header field, and the result is String type
int getContentLength()This method is used to obtain the value of the content length header field, and the result is of type int
String getCharacterEncoding()This method is used to return the character set encoding of the entity part of the request message. It is usually extracted from the content type header field, and the result is String type

Example:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        //Get request header information
        Enumeration headerNames = request.getHeaderNames();
        //Use the loop to traverse the request header and get a header field with the specified name through the getHeader() method
        while (headerNames.hasMoreElements()){
            String headerName = (String) headerNames.nextElement();
            out.println(headerName + " : " + request.getHeader(headerName) + "<br/>");
        }
    }

Accessed through the browser, the page displays:

Get the request body (request parameters) through request
In actual development, it is often necessary to obtain the form data submitted by the user, such as user name, password, e-mail, etc. in order to facilitate the acquisition of request parameters in the form, some columns of methods to obtain request parameters are defined in the HttpServletRequest interface, as shown in the following table:

Method declarationFunction description
String getParameter(String name)This method is used to obtain the parameter value of a specified name. If the request message does not contain a parameter with the specified name, the getParameter() method returns null; If the parameter with the specified name exists but no value is set, an empty string is returned; If the request message contains multiple parameters with the specified name, the getParameter() method returns the first parameter value
String[] getParameterValues(String name)There can be multiple parameters with the same name in the HTTP request message (usually generated by a FORM containing multiple field elements with the same name). If you want to obtain all parameter values corresponding to the same parameter name in the HTTP request message, you should use the getParameterValues() method, which is used to return an array of String type
Enumeration getParameterNames()This method is used to return an Enumeration object containing all parameter names in the request message. On this basis, all parameters in the request message can be traversed
Map getParameterMap()The individual Parameter Map() method is used to load all parameter names and values in the request message into a Map object and return

Example:
Create a jsp page with a form:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>form </title>
</head>
<body>
    <form action="/JavaEEDemo/request" method="post">
        user name:<input type="text" name="username"><br/>
        dense&nbsp;&nbsp;code:<input type="password" name="password"><br/>
        love&nbsp;&nbsp;Good:
        <input type="checkbox" name="hobby" value="sing">sing
        <input type="checkbox" name="hobby" value="dance">dance
        <input type="checkbox" name="hobby" value="football">Football
        <input type="submit" value="Submit">

    </form>
</body>
</html>

Write the doPost method of the Servlet:

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("user name:" + username);
        System.out.println("password:" + password);

        //Gets the value of the parameter named hobby
        String[] hobbys = request.getParameterValues("hobby");
        System.out.println("Hobbies:");
        for (int i = 0; i < hobbys.length; i++) {
            System.out.println(hobbys[i] + ", ");
        }
    }

To access a jsp page through a browser:

I'm in bold
I'm Microsoft YaHei
I'm Chinese Caiyun
color=#0099ff size=72 face = "bold"
color=#00ffff
color=gray

Topics: Java RESTful http