HttpServletRequest

The HttpServletRequest object represents the request of the client. When the client accesses the server through THE HTTP protocol, all the information in the HTTP request header is encapsulated in this object. The method provided by this object can obtain all the information requested by the client.

Two, JSP page to introduce JS, CSS file way

Excellent content recommendation
  • A set of Java architect learning resources waiting for you

  • The big Data video tutorials you need

Create a new Web project in Eclipse with the following directory structure:

At the beginning of the JSP page, get the root path of the project:

<%
   String path = request.getContextPath();
   String basePath = request.getScheme() + ": / /"
           + request.getServerName() + ":" + request.getServerPort()
           + path + "/"; % >Copy the code

Insert the following code in:

<base href="<%=basePath%>" />
Copy the code

This code sets the root path of the entire page to the project path.

3. Request common methods

1. Get client information

getRequestURL() Returns the full URL when the client made the request.
getRequestURI() Returns the resource name portion of the request line.
getQueryString () Returns the parameter part of the request line.
getRemoteAddr() Returns the IP address of the requesting client.
getPathInfo() Returns additional path information in the request URL. The extra path information is what is in the request URL after the Servlet’s path and before the query parameters, starting with a “/”.
getRemoteHost() Returns the full hostname of the requesting client.
getRemotePort() Returns the network port number used by the client.
getLocalAddr() Return the IP address of the WEB server.
getLocalName() Returns the host name of the WEB server.
private void RequestMessages(HttpServletRequest req, HttpServletResponse resp) throws IOException{ String reqUrl = req.getRequestURL().toString(); String reqUri = req.getrequesturi (); QueryString = req.getQueryString(); String remoteAddr = req.getremoteaddr (); String remoteHost = req.getremotehost (); int remotePort = req.getRemotePort(); String remoteUser = req.getRemoteUser(); String method = req.getMethod(); String pathInfo = req.getPathInfo(); String pathInfo = req.getPathInfo(); StringlocalAddr = req.getLocalAddr(); // Get the IP address of the WEB server StringlocalName = req.getLocalName(); / / access to the WEB server hostname resp. SetCharacterEncoding ("UTF-8"); // Sets the character to"UTF-8"Resp. SetHeader (utF-8, utF-8, utF-8, utF-8)"content-type"."text/html; charset=UTF-8");
    PrintWriter out = resp.getWriter();
    out.write(The client information obtained is as follows:);
    out.write("<br/>");
    out.write("Requested URL address:"+reqUrl);
    out.write("<br/>");
    out.write("Requested resources:"+reqUri);
    out.write("<br/>");
    out.write("Parameters attached to the requested URL address:"+queryString);
    out.write("<br/>");
    out.write("Visitor's IP address:"+remoteAddr);
    out.write("<br/>");
    out.write("Host name of visitor:"+remoteHost);
    out.write("<br/>");
    out.write("Port number used:"+remotePort);
    out.write("<br/>");
    out.write("remoteUser:"+remoteUser);
    out.write("<br/>");
    out.write("Request method used:"+method);
    out.write("<br/>");
    out.write("pathInfo:"+pathInfo);
    out.write("<br/>");
    out.write("localAddr:"+localAddr);
    out.write("<br/>");
    out.write("localName:"+localName);
}
Copy the code

2. Get the client request header

  • GetHeader (string name) : string

  • GetHeaders (String name) Method :Enumeration

  • GetHeaderNames () method

private void RequestHead(HttpServletRequest req, HttpServletResponse resp) throws IOException{
    resp.setCharacterEncoding("UTF-8"); // Sets the character to"UTF-8"Resp. SetHeader (utF-8)"content-type"."text/html; charset=UTF-8"); PrintWriter out = resp.getWriter(); Enumeration<String> reqHeadInfos = req.getHeaderNames(); // Get all headers out.write("All request headers from the client are as follows:");
    out.write("<br/>");
    while(reqHeadInfos.hasMoreElements()) { String headName = (String) reqHeadInfos.nextElement(); String headValue = req.getHeader(headName); Out.write (headName+) out.write(headName+":"+headValue);
        out.write("<br/>");
    }
    out.write("<br/>");
    out.write("Received client accept-encoding request header value:);
    out.write("<br/>");
    String value = req.getHeader("Accept-Encoding"); Out.write (value); // Get the accept-encoding header out.write(value); Enumeration<String> e = req.getHeaders("Accept-Encoding");
    while(e.hasMoreElements()) { String string = (String) e.nextElement(); System.out.println(string); }}Copy the code

3. Get the client request parameters

getParameter(String name) Get request parameters by name (common)
getParameterValues(String name) Get a list of request parameters by name (common)
getParameterMap() The return value is a map-type value that records the mapping between request parameters and request parameter values in a request submitted by a front-end (such as a JSP page). (Often used when writing frameworks)

The following form:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
   String path = request.getContextPath();
   String basePath = request.getScheme() + ": / /"
           + request.getServerName() + ":" + request.getServerPort()
           + path + "/";
%>
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title> Form submission </title> <link href="css/bootstrap.css" rel="stylesheet">
<script src="Js/jquery - 3.2.1. Js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
    <form class="form-horizontal" action="<%=request.getContextPath()%>/GetParameterRequest.html" role="form" method="post">
        <div class="form-group">
            <label for="firstname" class="col-sm-1 control-label"> name </label> <div class="col-sm-3">
                <input type="text" class="form-control" name="name"
                    placeholder="Please enter your name">
            </div>
        </div>
        <div class="form-group">
            <label for="lastname" class="col-sm-1 control-label"> Age </label> <div class="col-sm-3">
                <input type="text" class="form-control" name="age"
                    placeholder="Please enter your age">
            </div>
        </div>
        <div class="form-group">
            <label for="lastname" class="col-sm-1 control-label"> Gender </label> <div class="col-sm-3">
                <input type="radio" name="sex" value="Male"Checked male > < inputtype="radio" name="sex" value="Female"> female </div> </div> <div class="form-group">
            <label for="lastname" class="col-sm-1 control-label"> </label> <div class="col-sm-3">
                <input type="checkbox" name="aihao" value="Sing"Singing > < inputtype="checkbox" name="aihao" value="The Internet"< input > to get to the Internettype="checkbox" name="aihao" value="Game"Game > < inputtype="checkbox" name="aihao" value="Reading"> </div> </div> <div class="form-group">
            <div class="col-sm-offset-1 col-sm-3">
                <button type="submit" class="btn btn-default"</button> <buttontype="reset" class="btn btn-default"Reset > < / button > < / div > < / div > < / form > < / body > < / HTML >Copy the code

Receive form parameters using the getParameter and getParameterValues methods:

public class GetParameterRequest extends HttpServlet{ private static final long serialVersionUID = 3903946972744326948L;  @Override protected voiddoGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// The client submits the form data using UTF-8. Therefore, you need to set the server to use THE UTF-8 encoding to receive Chinese data. Otherwise, garbled characters will be generated for Chinese data."UTF-8"); String name = req.getParameter("name"); String age = req.getParameter("age"); String sex = req.getParameter("sex"); String[] aihaos = req.getparameterValues () {// getParameterValues() {// aihaos = req.getparameterValues () {// getParameterValues();"aihao");
        
        String aihao = "";
        if(aihaos ! = null){for (int i = 0; i < aihaos.length; i++) {
                if(i == aihaos.length - 1){
                    aihao += aihaos[i];
                } else {
                    aihao += aihaos[i] + ",";
                }
            }
        }
        System.out.println("Name:" + name);
        System.out.println("Age:" + age);
        System.out.println("Gender: + sex);
        System.out.println("Hobbies:" + aihao);
        req.setAttribute("aihao", aihao); / / set the server to utf-8 output data to the client resp. The setCharacterEncoding ("UTF-8");
        this.getServletContext().getRequestDispatcher("/request.jsp").forward(req, resp); }}Copy the code

Response page:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
   String path = request.getContextPath();
   String basePath = request.getScheme() + ": / /"
           + request.getServerName() + ":" + request.getServerPort()
           + path + "/";
%>
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title> Form submission </title> <link href="css/bootstrap.css" rel="stylesheet">
<script src="Js/jquery - 3.2.1. Js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
<table class="table"> < thead > < tr > < th > name < / th > < th > results < / th > < / tr > < thead > < tbody > < tr > < td > name < / td > < td > < % = request. The getParameter ("name") % > < / td > < / tr > < tr > < td > age < / td > < td > < % = request. The getParameter ("age") % > < / td > < / tr > < tr > < td > gender < / td > < td > < % = request. The getParameter ("sex") % > < / td > < / tr > < tr > < td > hobby < / td > < td > < % = request. The getAttribute ("aihao") %></td>
      </tr>
   </tbody>
</table>
</body>
</html>
Copy the code

Submit the following form:

Background printing:

The running results are as follows:

4. Garbled Chinese parameters in request receiving form submission

1. Garbled characters of Chinese parameters in the form submitted by POST

There is the following form:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
   String path = request.getContextPath();
   String basePath = request.getScheme() + ": / /"
           + request.getServerName() + ":" + request.getServerPort()
           + path + "/";
%>
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title> Form submission </title> <link href="css/bootstrap.css" rel="stylesheet">
<script src="Js/jquery - 3.2.1. Js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
    <form class="form-horizontal" action="<%=request.getContextPath()%>/PostRequest.html" role="form" method="post">
        <div class="form-group">
            <label for="firstname" class="col-sm-1 control-label"> name </label> <div class="col-sm-3">
                <input type="text" class="form-control" name="name"
                    placeholder="Please enter your name">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-1 col-sm-3">
                <button type="submit" class="btn btn-default"</button> <buttontype="reset" class="btn btn-default"Reset > < / button > < / div > < / div > < / form > < / body > < / HTML >Copy the code

Background receiving parameters:

public class PostRequest extends HttpServlet{
 
    private static final long serialVersionUID = 3903946972744326948L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        System.out.println("Name:"+ name); }}Copy the code

Submit data:

Running results:

The reason why the garbled code, is because the server and the client communication code is not consistent, so the solution is: set up a unified code between the client and the server, then according to this code for data transmission and reception.

Since the client transmits the form data to the server using UTF-8 character encoding, the server also needs to set it to receive the form data in UTF-8 character encoding. SetCharacterEncoding method unified encoding format:

public class PostRequest extends HttpServlet{
 
    private static final long serialVersionUID = 3903946972744326948L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// Set the server to receive data in UTF-8 encoding req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        System.out.println("Name:"+ name); }}Copy the code

Resubmit the form, Chinese garbled solution:

2. Garbled characters of Chinese parameters in the form submitted by GET

There is the following form:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
   String path = request.getContextPath();
   String basePath = request.getScheme() + ": / /"
           + request.getServerName() + ":" + request.getServerPort()
           + path + "/";
%>
<html>
<head>
<base href="<%=basePath%>" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title> Form submission </title> <link href="css/bootstrap.css" rel="stylesheet">
<script src="Js/jquery - 3.2.1. Js"></script>
<script src="js/bootstrap.js"></script>
</head>
<body>
    <form class="form-horizontal" action="<%=request.getContextPath()%>/GetRequest.html" role="form" method="get">
        <div class="form-group">
            <label for="firstname" class="col-sm-1 control-label"> name </label> <div class="col-sm-3">
                <input type="text" class="form-control" name="name"
                    placeholder="Please enter your name">
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-offset-1 col-sm-3">
                <button type="submit" class="btn btn-default"</button> <buttontype="reset" class="btn btn-default"Reset > < / button > < / div > < / div > < / form > < / body > < / HTML >Copy the code

Background receiving parameters:

public class GetRequest extends HttpServlet{
 
    private static final long serialVersionUID = 3903946972744326948L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name");
        System.out.println("Name:"+ name); }}Copy the code

Submit data:

Running results:

Garbled characters are generated. For data transmitted through GET, the default character encoding is ISO8859-1. The client transmits data to the server in UTF-8, while the server uses ISO8859-1 to receive data. The server and client communication code is not consistent, so it will produce Chinese garbled.

Solutions:

After the data is received, the byte array of the raw data received by the Request object in iso8859-1 character encoding is obtained, and the string is constructed from the byte array in the specified encoding

public class GetRequest extends HttpServlet{
 
    private static final long serialVersionUID = 3903946972744326948L;
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String name = req.getParameter("name"); // Encode the byte array of the raw data received with the iso8859-1 character, then construct the String name = new String(name.getbytes () with the specified encoding from the byte array."ISO8859-1"),"UTF-8");
        System.out.println("Name:"+ name); }}Copy the code

Resubmit the form, Chinese garbled solution:

5. Request object implements Request forwarding

4.1 Basic concepts of request forwarding

Request forwarding: When a Web resource receives a request from a client, it notifies the server to invoke another Web resource for processing.

Application scenario of request forwarding: MVC design pattern

There are two ways to implement request forwarding in servlets:

The getRequestDispatcher(String Path) method of the ServletContext returns a RequestDispatcher object. The forward method of this object is called to forward the request.

For example, the test.jsp page that forwards the request

RequestDispatcher reqDispatcher =this.getServletContext().getRequestDispatcher("/test.jsp");
reqDispatcher.forward(request, response);
Copy the code

The request object provides the getRequestDispatche(String Path) method, which returns a RequestDispatcher object. The forward method of this object can be used to forward the request.

For example, the test.jsp page that forwards the request

request.getRequestDispatcher("/test.jsp").forward(request, response);
Copy the code

The Request object is also a domain object (Map container). Developers use the Request object to transfer data to other Web resources for processing when implementing forwarding.

For example, request RequestDemo06 Servlet, which forwards the request to the test.jsp page

package gacl.request.study;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RequestDemo06 extends HttpServlet {

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

        String data="Hi, I'm lone Wolf, and I'm summing up JavaWeb."; /** * To store data in the request object, use the request object as a Map."data", data); / / client access RequestDemo06 after this Servlet RequestDemo06 notification server forwards the request (forward) to the test. The JSP page for processing the request. GetRequestDispatcher ("/test.jsp").forward(request, response);
    }

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

The test.jsp page code looks like this:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"% > <! DOCTYPE HTML PUBLIC"- / / / / W3C DTD HTML 4.01 Transitional / / EN"> < HTML > <head> <title> The Request object implements the Request forward </title> </head> <body> to retrieve the data stored in the Request object in a normal way: <h3 style="color:red;"><%=(String)request.getAttribute("data")%></h3> Use the EL expression to fetch data stored in the request object: <h3 style="color:red;">${data}</h3>
  </body>
</html>
Copy the code

When a Request object is used as a domain object (a Map container), it operates in four main ways

  • The setAttribute(String name,Object O) method stores data as an attribute of the Request Object, for example, request.setAttribute(“data”, data).
  • The getAttribute(String name) method obtains the name attribute value of the Request object, for example, request.getAttribute(“data”).
  • RemoveAttribute (String name) removes the name attribute of the Request object, for example: request.removeAttribute(“data”)
  • GetAttributeNames method, get all the attributes of the request object, is a return, such as: Enumeration attrNames = request. GetAttributeNames ();

4.2 Difference between request redirection and request forwarding

When a Web resource receives a client request, it notifies the server to invoke another Web resource for processing, which is called request forwarding /307.

When a Web resource receives a client request, it notifies the browser to access another Web resource for processing. This is called request redirection /302.

The resources

http://www.cnblogs.com/xdp-gacl/p/3798347.html
https://www.cnblogs.com/Zender/p/7647503.html
Copy the code
Excellent content recommendation
  • A set of Java architect learning resources waiting for you

  • The big Data video tutorials you need

  • Java full set of learning video tutorials and source

  • Micro-service resources springboot, SpringCloud, Docker, Dubbo project combat and so on

If there are any improper articles, please correct them. If you like reading on wechat, you can also follow my wechat official account: Learn Java well and get quality learning resources.