HttpServletRequest class and HttpServletResponse class

1. HttpServletRequest class

a) HttpServletRequest What does the class do.

Every time a request enters the Tomcat server, the Tomcat server will parse the requested HTTP protocol information and encapsulate it into the Request object. Then pass it to the service method (doGet and doPost) for us to use. Wecan obtain all requested information through the HttpServletRequest object.

b) HttpServletRequest Common methods of the class

i. getRequestURI() Gets the requested resource path

ii. getRequestURL() Gets the requested Uniform Resource Locator (absolute path)

@WebServlet("/RequestAPIServlet")
public class RequestAPIServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //getRequestURI() Gets the requested resource path
        String requestURI = req.getRequestURI();
        System.out.println("requestURI = " + requestURI);
        //getRequestURL() Gets the requested uniform resource locator (absolute path)
        StringBuffer requestURL = req.getRequestURL();
        System.out.println("requestURL = " + requestURL);
    }
}

iii. getRemoteHost() gets the client’s IP address

//getRemoteHost() Get the client’s ip address
String remoteHost = req.getRemoteHost();
System.out.println("remoteHost = " + remoteHost);

iv. getHeader() gets the request header

String accept = req.getHeader("Accept"); //Specified
String header = req.getHeader("Accept-Encoding"); //Specify what the browser can support
String date = req.getHeader("Date"); //The date and time the request is sent
System.out.println("accept = " + accept);
System.out.println("header = " + header);
System.out.println("date = " + date);

v. getParameter() gets the requested parameters

//getParameter() Gets the requested parameters
String myname = req.getParameter("myname"); //The parameters submitted by get also use the getParameter() method to receive parameters, which is no different from receiving parameters when submitted by post.
String mypass = req.getParameter("mypass");
System.out.println("myname = " + myname);
System.out.println("mypass = " + mypass);

HttpServletRequest req can receive data submitted by the client. Whether it is data submitted by get or post, getParameter() is used to receive the data.

vi. getParameterValues() gets the requested parameters (used when there are multiple values)

vii. getMethod() Gets the request method GET or POST

viii. setAttribute(key, value); Set domain data

ix. getAttribute(key); Get domain data

x. getRequestDispatcher() Gets the request forwarding object

Note: Request forwarding only redirects resources within the site; the address bar does not change during forwarding.

RequestDispatcher requestDispatcher = req.getRequestDispatcher("/Servlet2");
//Request forwarding cannot be redirected outside the site, but can only be redirected within the resources under the current project [Request Forwarding]
// RequestDispatcher requestDispatcher = req.getRequestDispatcher("http://www.baidu.com");

// Go to Sevlet2 (Counter 2)
requestDispatcher.forward(req,resp);

Different meanings of / slash in web

The client [browser] uses / which will resolve to http://ip:port

Server side uses / which will be parsed into http://ip:port/project path

Note: There is an exception on the server side: resp.sendRedirect(“Servlet”) redirection; adding / will resolve it to http://ip:port just like the client

a) Forwarding of requests

What is request forwarding?

Request forwarding means that after the server receives the request, the operation of jumping from one resource to another is called request forwarding.

1. HttpServletResponse Class

a) HttpServletResponse The role of the class

The HttpServletResponse class is the same as the HttpServletRequest class. Every time a request comes in, the Tomcat server will create a Response object and pass it to the Servlet program for use. HttpServletRequest represents the requested information, HttpServletResponse represents all the response information,

If we need to set the information returned to the client, we can set it through the HttpServletResponse object.

b) Description of the two output streams.

byte stream

getOutputStream();

Commonly used for downloading (passing binary data)

character stream

getWriter();

Commonly used to return strings (commonly used)

Only one of the two streams can be used at the same time.

If you use a byte stream, you cannot use a character stream, and vice versa, otherwise an error will be reported.

How to write data to the client

Chinese garbled characters are printed using the output character stream in the response object.

@WebServlet("/ResponseAPIServlet")
    public class ResponseAPIServlet extends HttpServlet {
        @Override
        protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            PrintWriter writer = resp.getWriter();
            writer.println("I am a test data, let's see how it works! 112233");
        }
    }
// It will set both the server and the client to use the UTF-8 character set, and also set the response header
// This method must be called before obtaining the stream object to be effective.
resp.setContentType("text/html; charset=UTF-8");

Request redirect

Request redirection means that the client sends a request to the server, and then the server tells the client. I’ll give you some addresses, you go to the new address to visit. Call the request to redirect (because the previous address may have been obsolete).

Features of request redirection:

1. The browser address bar will change

Redirect jump of response

resp.setStatus(302); //Set the response status code
//Set the response header to indicate where the new address is
resp.setHeader("Location","http://www.hbpu.edu.cn");

Redirect jump is a client-side jump. It can jump to any web page, whether it is your own website resources or other people’s website resources.

2. Service forwarding forward is an intra-site jump and cannot jump to resources outside the site, and its jumps are all within one request, so the request request intra-office data can be shared, which is why it is different from redirect jumps. In the same place, when we develop, we use forw to be larger than the redirect jump.

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 138898 people are learning the system