ServletRequest&ServletResponse

Request and Response

Course objectives

1. Understand what is Request and Response

2. Understand Reqest to obtain request information

3. Master the use of Request domain objects to share data

4. Use Response to set response information

5. Master Redirection

One.ServletRequest

1.1 Concept

The server encapsulates the service into a servlet service object, then the data carried by the client’s request can also be encapsulated into a ServletRequest service request object, which is essentially an interface, which is sent by different clients for implementation, and the sent data is encapsulated into the corresponding object send to server

However, since the http protocol is mostly used in web transmission now, and the protocol will transmit a lot of information when requesting, a sub-interface HttpServletRequest inherited from the ServletRequest interface is created according to the http protocol, corresponding to the use of the HttpServlet service.

Essence: It is to write an object to store the data sent by the browser (the server can obtain this object and obtain data from this object and use other functions)

**Function: **Get client information

public interface HttpServletRequest extends ServletRequest {<!-- -->....}

1.2 Architecture

ServletRequest

? |

HttpServletRequest

? |

org.apache.catalina.connector.RequestFacade (provided by tomcat vendor)

1.3 Get request header API

< /table>

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet(name = "RequestServlet", value = "/request1")
public class RequestServlet extends HttpServlet {<!-- -->
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<!-- -->
        //The request object encapsulates and saves the client (the data sent by the browser)
        //The corresponding data carried by the client request can be obtained through the corresponding method
        //Get client request protocol
        String protocol = request. getProtocol();
        System.out.println(protocol);
        //Get the client request service name (ip or domain name)
        String serverName = request. getServerName();
        System.out.println(serverName);
        // Get the service url requested by the client
        String servletPath = request. getServletPath();
        System.out.println(servletPath);
        / / Get the port number of the client request service
        int serverPort = request. getServerPort();
        System.out.println(serverPort);
        //Get the project address requested by the client (project name, the request address configured by tomcat is not the actual project name)
        String contextPath = request. getContextPath();
        System.out.println(contextPath);
        // Get the relative path of the url requested by the client
        String requestURI = request. getRequestURI();
        System.out.println(requestURI);
        // Get the absolute path of the client request url
        String requestURL = request. getRequestURL(). toString();
        System.out.println(requestURL);
        // Get the value of the specified field in the request header
        String userAgent = request. getHeader("User-Agent");
        System.out.println(userAgent);
        String CacheControl = request. getHeader("Cache-Control");
        System.out.println(CacheControl + "11111");
    }
}

1.4 Get request parameters

getMethod() How to get the request
getRequestURI() Get the requested uri (relative path)
getRequestURL() Get the requested url (absolute path)
getRemoteAddr() Get the requested address
getProtocol() Get request protocol
getRemotePort() Get request Requested port
getHeader(“Host”); Get requested port + address
public String getParameter(String name) Get request specifying a single parameter
public String[] getParameterValues(String name) Get request to specify multiple parameters
public Map request.getParameterMap () Get all submitted data on the page
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
@WebServlet(name = "RequestServlet2", value = "/request2")
public class RequestServlet2 extends HttpServlet {<!-- -->
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<!-- -->
        // Generally, when we get request data, the most commonly used is to get the data written in the request (form submission data)
        //get request data is transmitted in the url address bar
        //Get the value corresponding to the specified parameter carried in the request
        String username = request. getParameter("username");
        String password = request. getParameter("password");
        System.out.println(username + "|" + password);

    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<!-- -->
        // Generally, when we get request data, the most commonly used is to get the data written in the request (form submission data)
        //post request data is transmitted in the request body
        //You can also get all the data through the method
        Enumeration<String> names = request. getParameterNames();
        while (names.hasMoreElements()) {<!-- -->
            String s = names. nextElement();
            System.out.println(s + "=>" + request.getParameter(s));
        }
        //The getParameter method can only get the first data corresponding to the key. If multiple data keys are the same, you need to use other methods to get it
        String[] likes = request. getParameterValues("like");
        System.out.println(Arrays.toString(likes));
    }
}

req01.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="request2" method="post">
        <input type="text" name="username"><br>
        <input type="password" name="password"><br>
        <input type="checkbox" name="like" value="cy"> smoke<br>
        <input type="checkbox" name="like" value="hj"> drink<br>
        <input type="checkbox" name="like" value="tt"> perm<br>
        <input type="submit" value="submit"><br>
    </form>
</body>
</html>

1.5 Chinese garbled characters

Reason for garbled characters: The data is transmitted on the network in a popular form. If the encoding format is set to match the current development environment, there will be no garbled characters. If not set, the default encoding of the browser is IOS-8859-1, and you can use String The construction method of the class converts the byte array of the specified encoding into the string of the corresponding encoding, but usually the encoding conversion is performed on the server side in the form of a method instead of this way

  • The way to submit is get: Chinese will not be garbled (UTF-8 for versions above tomcat8.0)

    • String username = new String(req. getParameter("username"). getBytes("ISO8859-1"),"UTF-8")
      
  • The method of submission is post: Chinese garbled characters

    •  //If Chinese garbled characters appear, you only need to modify the encoding format of the data in the request to the corresponding encoding before obtaining the corresponding data
              request.setCharacterEncoding("UTF-8");
      

Note: Be sure to write before getting the data, otherwise it is meaningless

1.6 request domain object

When the browser requests the server, it will encapsulate all the request information into a corresponding request object, and can obtain the corresponding data from the request object. After the server obtains the request object, it can continue to add data, but the scope of the request Only this request, because the http protocol is based on the request and response protocol, every time the browser enters the address to request the server, the request will be rewritten and a new request object will be created.

Method name Function Remarks
Object getAttribute(String name) request domain object get value
void setAttribute(String name, Object o) request domain object value
void removeAttribute(String name) request domain object delete value

Summarize

  • request is mainly used to store prompt information
 //When the client requests each time, each request will be encapsulated into a request object to save the corresponding information
        // Request again Even if the request data is the same, the created request object is a different object
        //request is passed as a domain object to transfer data in this request
        //Domain Object Unified API
        //Set the object data corresponding to the specified key
        // request.setAttribute(key,obj);
        //Delete the data corresponding to the specified key
        //request. removeAttribute(key);
        // Get the data stored by the specified key
        // Object key = request. getAttribute(key);
        //Get the list object of all keys stored in the specified domain object
        //Enumeration<String> attributeNames = request.getAttributeNames();

        Random random = new Random();
        request.setAttribute("random", random.nextInt(100));
        request.setAttribute("test", "test");

        Enumeration<String> attributeNames = request. getAttributeNames();
        while(attributeNames.hasMoreElements()){<!-- -->
            String key = attributeNames. nextElement();
            Object o = request. getAttribute(key);
            System.out.println(key + ":" + o);
        }

        Object r = request. getAttribute("random");
        System.out.println(r);
        request. removeAttribute("random");
        Object r1 = request. getAttribute("random");
        System.out.println(r1);

        Enumeration<String> attributeNames1 = request. getAttributeNames();
        while(attributeNames1.hasMoreElements()){<!-- -->
            String key = attributeNames1. nextElement();
            Object o = request. getAttribute(key);
            System.out.println(key + ":" + o);
        }

1.7 forwarding

1.7.1 Concept

  • Forwarding is also a program jump, inside the server
  • Jump path: use the absolute path on the server side, not including the project name! !
  • Execution process: When the client requests service a, service a obtains the client request data and stores it in the request object, but a cannot complete the corresponding service, forwards the request to service b through the forwarding method, and forwards the requested objects together Execution, when b is executed, the result will be returned to service a, and service a will send the final result to the client

1.7.2 Principle

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-X8esk7bN-1679416118750) (assert\The principle of forwarding.bmp)]

1.7.3 Method

  • request.getRequestDispatcher(“path to be forwarded”).forward(request,response);

1.7.4 case

AServlet.java

@WebServlet(name = "AServlet", value = "/a")
public class AServlet extends HttpServlet {<!-- -->
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<!-- -->
        //With the servletcontext, there is an assignment, acquisition and removal method for the next use
        //It's just that the corresponding operation is performed on the request object now
        request.setAttribute("username", "lisi");
        System.out.println("a execute");
        //If you want to pass the data in A to B, you need to forward the request object in AServlet to B

        //Request forwarding
        //Forward the current request to other services and fill in the request object and response object of the current request
        request.getRequestDispatcher("/b").forward(request,response);
    }
}

BServlet.java

@WebServlet(name = "BServlet", value = "/b")
public class BServlet extends HttpServlet {<!-- -->
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<!-- -->
        // Cannot get data in other servlet requset objects
        //Because each request will create a new request object
        Object username = request. getAttribute("username");
        System.out.println(username);
        System.out.println("b execute");
    }
}

Forwarding is not limited to service forwarding, pages can also be forwarded, and since forwarding is an internal request of the server, internal resources of the server can be accessed (forwarding can access pages under WEB-INF).

Two. ServletResponse

2.1 Concept

The data sent by the client is stored in the request object, then the data of the server processing the corresponding request will be encapsulated in the response object (including the response format)

For the response, the ServletResponse interface is provided for data storage, but Oracle provides the inheritance and ServletResponse interface based on the Http protocol. HttpServletResponse is used to process the response based on the http protocol request.

Function: The server responds to the client

@WebServlet(name = "ResponseServlet", value = "/rs")
public class ResponseServlet extends HttpServlet {<!-- -->
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<!-- -->
        //HttpServletResponse is used to save response related data
        //The commonly used relevant data of the response has been defined according to the http protocol, we only need to continue to add according to the needs

        //Set the encoding of the response buffer
        response.setCharacterEncoding("UTF-8");
        //Set the type of the client's corresponding content
        response.setContentType("text/html;charset=utf-8");

        //getWriter() gets the print stream and prints the information directly to the client page
        PrintWriter writer = response. getWriter();
        writer.print("response returns the data<br>");
    }
}

Timed refresh

RefreshServlet. Java

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

/**
 * Timed jump of the page
 */
public class Refresh1Servlet extends HttpServlet {<!-- -->

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<!-- -->
 response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // first output the content
        System.out.println("Refresh1Servlet executed...");
        // set header information
        response.setHeader("refresh", "5;url=/ResponseTest/response/demo1/suc.html");
        // Output a sentence
        response.getWriter().print("Jump after 5 seconds");
}
 
}

2.2 Redirect

Concept

When the user requests service A for service execution, but service A cannot execute the corresponding service, and service A is not associated with the service that can actually be executed, only the corresponding address can be provided, and the client requests the corresponding service again to complete the realization of the requirement.

Schematic

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-6nADyI5w-1679416118752) (assert\redirection principle.png)]

Method

response.sendRedirect(“/redirect address”);

Can only access public resources, not internal resources

Case

  • Requirement: The user enters the user name and password on the login interface, and the servlet in the background judges. If the user name and password are both admin, jump to the success page, otherwise jump to the login failure page
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>Login page</h3>
<form action="/ServletTest/login" method="get">
Username: <input type="text" name="username"/><br/>
\t
Password: <input type="text" name="password"/>
<input type="submit" value="login"/>
</form>
</body>
</html>
package com.login;

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 LoginServlet extends HttpServlet {<!-- -->
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {<!-- -->
// get username and password
String username = req. getParameter("username");
String password = req. getParameter("password");
\t\t//judge
if("admin".equals(username) & amp; & amp; "admin".equals(password)){<!-- -->
//jump to success page
resp.sendRedirect("/ServletTest/succ.html");
}else{<!-- -->
//jump to failure page
resp.sendRedirect("/ServletTest/fail.html");
}
}
\t
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {<!-- -->
doGet(req, resp);
}
}
@WebServlet(name = "AServletResponse", value = "/as")
public class AServletResponse extends HttpServlet {<!-- -->
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<!-- -->
        System.out.println("A execution");
        //sendRedirect redirects the current request to the specified path without carrying parameters
        request.setAttribute("username","lisi");
        response. sendRedirect("bs");
    }
}

@WebServlet(name = "BServletResponse", value = "/bs")
public class BServletResponse extends HttpServlet {<!-- -->
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {<!-- -->
        System.out.println("b execute");
        //Because redirection is equivalent to the customer requesting again, a new request object will be created, so the data assigned by the previous service will not be obtained
        Object username = request. getAttribute("username");
        System.out.println(username);
    }
}

2.3 The difference between forwarding and redirection

  • The forwarded address bar doesn’t change, but the redirect does

  • Forwarding is one request and one response, but redirection is multiple requests and responses

  • The forwarded status code is 2xx, and the redirection is 3xx

  • Forwarding can use the request domain object to transfer data, but redirection cannot (request and response objects must be passed)

  • Forwarding the essence of the request is to forward the specified service and the current service will return it after the execution, redirecting the current service to end the client to continue requesting other services

  • Forwarding occurs inside the server, and the forwarded resource does not need to carry the project name, and the redirection can be redirected to any public resource (need to carry the project name).

    Forwarding can request internal resources under web-inf

2.4 The difference between get and post

  • The data sent by the get request is transmitted in the url address bar, and the post request is transmitted in the request body

  • Get requests are less secure than post

  • The get request can be saved by the bookmark, but the post cannot (because the bookmark saves the url to save the requested data)

  • The get request has no effect when the browser page backs up, and the post may lead to repeated submission of the form

  • The browser will actively cache the corresponding data for get requests, and the post will not actively cache

  • The get request page encoding is the same as the background encoding and will not be garbled, and the post may be garbled

  • The upper limit of request data for get requests varies according to different browser settings (generally 2k), and post requests can be regarded as unlimited in size

  • The get request is sent once, and the post request is sent twice (the request will send the data together with the url, and the post will send it again after requesting the address response)

    The last item can also be understood as, the get request server receives passively (your server does not accept data, my data is sent along with the request address)

Forwarding occurs inside the server, and the forwarded resource does not need to carry the project name, and the redirection can be redirected to any public resource (need to carry the project name).

Forwarding can request internal resources under web-inf

2.4 The difference between get and post

  • The data sent by the get request is transmitted in the url address bar, and the post request is transmitted in the request body

  • Get requests are less secure than post

  • The get request can be saved by the bookmark, but the post cannot (because the bookmark saves the url to save the requested data)

  • The get request has no effect when the browser page backs up, and the post may lead to repeated submission of the form

  • The browser will actively cache the corresponding data for get requests, and the post will not actively cache

  • The get request page encoding is the same as the background encoding and will not be garbled, and the post may be garbled

  • The upper limit of request data for get requests varies according to different browser settings (generally 2k), and post requests can be regarded as unlimited in size

  • The get request is sent once, and the post request is sent twice (the request will send the data together with the url, and the post will send it again after requesting the address response)

    The last one can also be understood as, the get request server receives passively (your server does not accept data, my data is sent along with the request address)

    The post requests the server to actively accept, and the data will be sent to the server only after the server responds