Summary of HttpServletRequest object

Keywords: Java encoding Web Server Programming

The HttpServletRequest object represents the client's request. When the client accesses the server through the HTTP protocol, all the information in the HTTP request header is encapsulated in a web container. By the method provided by this object, all the information requested by the client can be obtained.

Request Common Methods for Getting Client Information
The getRequestURL method returns the full URL at which the client makes the request.
The getRequestURI method returns the part of the resource name in the request line.
The getQueryString method returns the parameter part of the request row.
The getPathInfo method returns additional path information from the request URL.Additional path information is the content in the request URL that follows the path of the Servlet and precedes the query parameters, starting with'/'.
The getRemoteAddr method returns the IP address of the requesting client.
The getRemoteHost method returns the full host name of the requesting client.
The getRemotePort method returns the network port number used by the client.
The getLocalAddr method returns the IP address of the WEB server.
The getLocalName method returns the host name of the WEB server.

[Java] Plain Text View Copy Code
?

package cn.itcast;

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.io.PrintWriter;

@WebServlet(name = "RequestDemo01",urlPatterns = "/demo01")
public class RequestDemo01 extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    doGet(request,response);
}

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

    /**
     * 1.Get Client Information
     */
    String requestUrl = request.getRequestURL().toString();//Get the requested URL address
    String requestUri = request.getRequestURI();//Requested Resources
    String queryString = request.getQueryString();//Get the parameters attached to the requested URL address
    String remoteAddr = request.getRemoteAddr();//IP address of the visitor
    String remoteHost = request.getRemoteHost();
    int remotePort = request.getRemotePort();
    String remoteUser = request.getRemoteUser();
    String method = request.getMethod();//The method used to get the requested URL address
    String pathInfo = request.getPathInfo();
    String localAddr = request.getLocalAddr();//Get the IP address of the WEB server
    String localName = request.getLocalName();//Get the hostname of the WEB server
    response.setCharacterEncoding("UTF-8");//Set character output to client browser in UTF-8 encoding
    //Control the browser's display of data in UTF-8 encoding by setting a response header. If you don't add this sentence, the browser will display garbled code
    response.setHeader("content-type", "text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.write("Client information obtained is as follows:");
    out.write("<hr/>");
    out.write("Requested URL Address:"+requestUrl);
    out.write("<br/>");
    out.write("Requested resources:"+requestUri);
    out.write("<br/>");
    out.write("Requested URL Parameters attached to the address:"+queryString);
    out.write("<br/>");
    out.write("Visitor's IP Address:"+remoteAddr);
    out.write("<br/>");
    out.write("Host name of the visitor:"+remoteHost);
    out.write("<br/>");
    out.write("Port number used:"+remotePort);
    out.write("<br/>");
    out.write("remoteUser: "+remoteUser);
    out.write("<br/>");
    out.write("Method used in the request:"+method);
    out.write("<br/>");
    out.write("pathInfo: "+pathInfo);
    out.write("<br/>");
    out.write("localAddr: "+localAddr);
    out.write("<br/>");
    out.write("localName: "+localName);

}

}

Get Client Request Header
getHeader(string name) method: String
getHeaders(String name) method: Enumeration
getHeaderNames() method
[Java] Plain Text View Copy Code
?

package cn.itcast;
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.io.PrintWriter;
import java.util.Enumeration;

@WebServlet(name = "RequestDemo02",urlPatterns = "/demo02")
public class RequestDemo02 extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    doGet(request,response);
}

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

    response.setCharacterEncoding("UTF-8");//Set character output to client browser in UTF-8 encoding
    //Control browser display data in UTF-8 encoding by setting response header
    response.setHeader("content-type", "text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    Enumeration<String> reqHeadInfos = request.getHeaderNames();//Get all request headers
    out.write("All request header information for the client is obtained as follows:");
    out.write("<hr/>");
    while (reqHeadInfos.hasMoreElements()) {
        String headName = (String) reqHeadInfos.nextElement();
        String headValue = request.getHeader(headName);//Gets the value of the corresponding request header based on its name
        out.write(headName+":"+headValue);
        out.write("<br/>");
    }
    out.write("<br/>");
    out.write("Obtained Clients Accept-Encoding Value of request header:");
    out.write("<hr/>");
    String value = request.getHeader("Accept-Encoding");//Get the value corresponding to the Accept-Encoding request header
    out.write(value);

    Enumeration<String> e = request.getHeaders("Accept-Encoding");
    while (e.hasMoreElements()) {
        String string = (String) e.nextElement();
        System.out.println(string);
    }
}

}

Get client request parameters (data submitted by client)
getParameter(String) method (common)
getParameterValues(String name) method (common)
getParameterNames() method (not commonly used)
getParameterMap() method (commonly used when writing frames)

Create a new demo03.html under the web folder as follows

[HTML] Plain Text View Copy Code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

Form Form Element </title>Html

<meta http-equiv="content-type" content="txt/html; charset=utf-8" />
</head>
<fieldset style="width:500px;">

Form form element </legend>Html
 <!--The action property of the form specifies where to send the form data when the form is submitted. The method property specifies how the form is submitted, which is divided into get and post. The default is get-->
<form action="http://localhost:8080/demo03" method="post">
    <!--Input text box, SIZE for display length, maxlength for maximum input length-->
    Number (text box):
    <input type="text" name="userid" value="NO." size="2" maxlength="2"><br>
    <!--Enter a text box and specify its defau lt value by value-->
    User name (text box): <input type="text" name="username" value="Please enter user name"><br>
    <!--Password box, where all input is in cipher text-->
    Password (password box):
    <!--indicates a space-->
    <input type="password" name="userpass" value="Please enter password"><br>
    <!--Radio button, specified by defau lt through checked, must have the same name, where value is what you really need-->
    Gender (radio box):
    <input type="radio" name="sex" value="man" checked>man
    <input type="radio" name="sex" value="female">female<br>
    <!--Drop-down list box, specify the drop-down options through the <option>element-->
    Department (drop-down box):
    <select name="dept">
        <option value="Technology Department">Technology Department</option>
        <option value="Sales" SELECTED>Sales</option>
        <option value="Finance Department">Finance Department</option>
    </select><br>
    <!--Check box, you can select mu lt iple options at the same time, the name must be the same, where value is what you really need-->
    Interest (check box):
    <input type="checkbox" name="inst" value="singing">singing
    <input type="checkbox" name="inst" value="swimming">swimming
    <input type="checkbox" name="inst" value="dance">dance
    <input type="checkbox" name="inst" value="programming" checked>programming
    <input type="checkbox" name="inst" value="go online">go Online
    <br>
    <!--Large text input box, width 34 columns, height 5 lines-->
    Description (text field):
    <textarea name="note" cols="34" rows="5">
 </textarea>
    <br>
    <!--Hidden field, not visible on page, designed to pass or save parameters-->
    <input type="hidden" name="hiddenField" value="hiddenvalue"/>
    <!--Submit Form button, when clicked Submit, all completed form content will be transferred to the server side-->
    <input type="submit" value="submit (submit button)">
    <!--Reset the form button, when you click Reset, all forms will be restored to their original display content-->
    <input type="reset" value="reset (reset button)">
</form>
<!--End of Form-->

</fieldset>
</body>
</html>
<!--End Marker-->

[Java] Plain Text View Copy Code
?

package cn.itcast;

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.text.MessageFormat;

@WebServlet(name = "RequestDemo03",urlPatterns = "/demo03")
public class RequestDemo03 extends HttpServlet {

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

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

//Client submits form data in UTF-8 encoding, so you need to set the server to receive in UTF-8 encoding, otherwise the Chinese data will be garbled

    request.setCharacterEncoding("UTF-8");
    /**
     * Number (text box):
     <input type="text" name="userid" value="NO." size="2" maxlength="2">
     */
    String userid = request.getParameter("userid");//Gets the number to fill in, userid is the name of the text box, <input type="text" name="userid">
    /**
     * User name (text box): <input type="text" name="username" value="Please enter a user name">
     */
    String username = request.getParameter("username");//Get Filled User Name
    /**
     * Password (password box): <input type="password" name="userpass" value="Please enter password">
     */
    String userpass = request.getParameter("userpass");//Get the completed password
    String sex = request.getParameter("sex");//Get Selected Gender
    String dept = request.getParameter("dept");//Get the selected Department
    //Get the selected interest, because you can select multiple values, so the value you get is an array of strings, so you need to use the getParameterValues method to get it
    String[] insts = request.getParameterValues("inst");
    String note = request.getParameter("note");//Get Filled-in Instructional Information
    String hiddenField = request.getParameter("hiddenField");//Get the contents of a hidden field

    String instStr="";
    /**
     * The technique of getting array data can avoid null pointer errors when insts array is null!
     */
    for (int i = 0; insts!=null && i < insts.length; i++) {
        if (i == insts.length-1) {
            instStr+=insts[i];
        }else {
            instStr+=insts[i]+",";
        }
    }

    String htmlStr = "<table>" +
            "<tr><td>Number to fill in:</td><td>{0}</td></tr>" +
            "<tr><td>Fill in the user name:</td><td>{1}</td></tr>" +
            "<tr><td>Fill in the password:</td><td>{2}</td></tr>" +
            "<tr><td>Selected gender:</td><td>{3}</td></tr>" +
            "<tr><td>Selected departments:</td><td>{4}</td></tr>" +
            "<tr><td>Selected interests:</td><td>{5}</td></tr>" +
            "<tr><td>Fill in the instructions:</td><td>{6}</td></tr>" +
            "<tr><td>Hide the contents of the domain:</td><td>{7}</td></tr>" +
            "</table>";
    htmlStr = MessageFormat.format(htmlStr, userid,username,userpass,sex,dept,instStr,note,hiddenField);

    response.setCharacterEncoding("UTF-8");//Set up server side to output data to client in UTF-8 encoding
    response.setContentType("text/html;charset=UTF-8");//Set up client browser to parse data in UTF-8 encoding
    response.getWriter().write(htmlStr);//Output content from htmlStr to client browser display

}

}

Copy one more copy of demo03.html above, put it under the web file and rename it demo04.html
Then change one place and change demo03 to Demo04 <form action="http://localhost:8080/demo04" method="post">

Create a RequestDemo04.java file with the following contents
[Java] Plain Text View Copy Code
?

package cn.itcast;

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.text.MessageFormat;
import java.util.Map;

@WebServlet(name = "RequestDemo04",urlPatterns = "/demo04")
public class RequestDemo04 extends HttpServlet {

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

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

//Client submits form data in UTF-8 encoding, so you need to set the server to receive in UTF-8 encoding, otherwise the Chinese data will be garbled

    request.setCharacterEncoding("UTF-8");
    //The parameters encapsulated by the request object are stored as Map s
    Map<String, String[]> paramMap = request.getParameterMap();
    for(Map.Entry<String, String[]> entry :paramMap.entrySet()){
        String paramName = entry.getKey();
        String paramValue = "";
        String[] paramValueArr = entry.getValue();
        for (int i = 0; paramValueArr!=null && i < paramValueArr.length; i++) {
            if (i == paramValueArr.length-1) {
                paramValue+=paramValueArr[i];
            }else {
                paramValue+=paramValueArr[i]+",";
            }
        }
        response.setCharacterEncoding("UTF-8");//Set up server side to output data to client in UTF-8 encoding
        response.setContentType("text/html;charset=UTF-8");//Set up client browser to parse data in UTF-8 encoding
        //Output Content to Client Browser Display
        response.getWriter().write(MessageFormat.format("{0}={1}</br>", paramName,paramValue));

    }
}

}

HttpServletRequest.png (38.65 KB, download times: 0)

HttpServletRequest.png

Posted by lindm on Fri, 06 Dec 2019 10:34:15 -0800