Servlet--HttpServletRequest gets request information (request header, request line, parameters) in detail

Overview of the ttpServletRequest object
In the Servlet API, a 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: the request line, the request header and the request message body, the related methods for obtaining the request line, the request header and the request message body are defined in the HttpServletRequest interface.
When we create a Servlet, we will override the service() method, or doGet()/doPost(). These methods have two parameters, a request representing the request and a response representing the response.
The type of request in the service method is ServletRequest, and the type of request in the doGet/doPost method is HttpServletRequest. HttpServletRequest is a sub-interface of ServletRequest. It has more powerful functions and methods. Today we will learn about HttpServletRequest.
The running process of request

Capture HTTP requests through packet capture tools

Obtain request line information through request
When accessing a Servlet, the request line of the request message will include information such as the request method, request resource name, and request path. In order to obtain these information, in the HTTPServletRequest interface , defines a series of methods for obtaining the request line, as shown in the following table:

method declaration Functional description
String getmethod() This method is used to obtain the request method in the HTTP request message (such as GET, POST, etc.)
String getReauestURI() This method is used to obtain the resource name part of 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 get the parameter part in the request line, that is, everything after the question mark after the resource path
String getProtocol() This method is used to get 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 "/", which means relative to the root directory of the entire WEB site, and the path does not contain "/" at the end. If the request URL belongs to the root directory of the web site, the return result is an empty string ""
String getServletPath() This method is used to get the name of the Servlet or the path to which the Servlet is mapped
String getRemoteAddr( ) This method is used to obtain the IP address of the requesting client, and its format is similar to "192.168.0.1"
String getRemoteHost() This method is used to obtain the full host name of the requesting client, and its format is similar to "pc1.xxxx.cn". It should be noted that if no
int getRemotePort() This method is used to obtain the port number of the request client network connection
String getLocalAddr() This method is used to obtain the IP address of the web server receiving the current request 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 receiving the current network connection on the web server
String getServerName() This method is used to obtain the hostname pointed to by the current request, that is, the part of the hostname 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 connected to the current request, that is, if the port number part corresponding to the HOST header field in the HTTP request message
String getScheme() This method is used to get the protocol name of the request, such as http, https or ftp
StringBuffer getRequestURL() This method is used to obtain the complete URL when the client sends a request, including the 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 StringBuffer type, not 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();
        //获取请求行的相关信息
        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 a 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, for example, the data type that the client can receive, compression method, language, etc. To this end, in the HttpServletRequest interface, a series of methods for obtaining HTTP request header fields are defined, as shown in the following table:

method declaration Functional 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 multiple header fields with the specified name, the getHeader() method returns one of them the value of the first header field
Enumeration getHeaders(String name) This method returns an Enumeration collection object consisting 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 containing all request header fields
int getIntHeader(String name) This method is used to get the header field with the specified name and convert its value to int type. It should be noted that if the header field with 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 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 calculated from January 1, 1970 at 0:00:00. time value in milliseconds
String getContentType() This method is used to obtain the value of the Content-Type header field, and the result is of type String
int getContentLength() This method is used to obtain the value of the Content-Length header field, and the result is int type
String getCharacterEncoding() This method is used to return the character set encoding of the entity part of the request message, 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();
        //获取请求头信息
        Enumeration headerNames = request.getHeaderNames();
        //使用循环遍历请求头,并通过getHeader()方法获取一个指定名称的头字段
        while (headerNames.hasMoreElements()){
            String headerName = (String) headerNames.nextElement();
            out.println(headerName + " : " + request.getHeader(headerName) + "<br/>");
        }
    }

Accessed through a browser, the page displays:

Obtain the request body (request parameters) through request
In actual development, it is often necessary to obtain form data submitted by users, such as user name, password, email, etc., in order to facilitate the acquisition of request parameters in the form , in the HttpServletRequest interface, a series of methods for obtaining request parameters are defined, as shown in the following table:

method declaration Functional description
String getParameter(String name) This method is used to obtain a parameter value with 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 The message contains multiple parameters with the specified name, and the getParameter() method returns the value of the first parameter that appears
String[] getParameterValues(String name) There can be multiple parameters with the same name in the HTTP request message (usually generated by a FORM form containing multiple field elements with the same name), if you want to get all the parameter values ​​corresponding to the same parameter name in the HTTP request message, then use The getParameterValues() method should be used, 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 the parameter names and values ​​in the request message into a Map object and return

示例:
创建一个带有表单的jsp页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>表单</title>
</head>
<body>
    <form action="/JavaEEDemo/request" method="post">
        用户名:<input type="text" name="username"><br/>
        密&nbsp;&nbsp;码:<input type="password" name="password"><br/>
        爱&nbsp;&nbsp;好:
        <input type="checkbox" name="hobby" value="sing">唱歌
        <input type="checkbox" name="hobby" value="dance">跳舞
        <input type="checkbox" name="hobby" value="football">足球
        <input type="submit" value="提交">

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

编写Servlet的doPost方法:

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("用户名:" + username);
        System.out.println("密码:" + password);

        //获取参数名为hobby的值
        String[] hobbys = request.getParameterValues("hobby");
        System.out.println("爱好:");
        for (int i = 0; i < hobbys.length; i++) {
            System.out.println(hobbys[i] + ", ");
        }
    }

通过浏览器访问jsp页面:

Size:规定文本的尺寸大小。可能的值:从 1 到 7 的数字。浏览器默认值是 3。

呈现效果:

我是黑体字
我是微软雅黑
我是华文彩云
color=#0099ff size=72 face=“黑体”
color=#00ffff
color=gray

Guess you like

Origin blog.csdn.net/liufeifeihuawei/article/details/120057802