Detailed explanation of Java response object

1 response object

1.1 overview of response objects

1.1.1 about response

Response, which indicates that the server has received the request and has completed the processing, and informs the user of the processing result. In short, it means that the server informs the client of the processing result of the request. In B/S architecture, the response is to bring the result back to the browser.

Response object, as its name implies, is an object used to realize the above functions in Java Web engineering.

1.1.2 common response objects

The response object is also defined in the Servlet specification, which includes protocol independent and protocol related.

  • Protocol independent object standard: ServletResponse interface

  • The protocol related object standard is: HttpServletResponse interface

Class structure diagram is as follows:

The response objects involved in the following introduction are related to HTTP protocol. That is, the implementation class of HttpServletResponse interface is used.

Some students may have questions here. When using Servlet, we need to define a class and implement the Servlet interface (or inherit its implementation class). Now we want to implement the response function. Do you want to define a class and implement the HttpServletResponse interface?

The answer to this question is no, we don't need to. We only need to use it directly in the Servlet written by ourselves, because the implementation class of this object is provided by Tomcat and we don't need to customize it. At the same time, it will help us create objects and pass them into doGet and doPost methods.

1.2 introduction to common methods

1.2.1 API introduction

On the official website, we can see: https://javaee.github.io/javaee-spec/javadocs/

Many methods are provided in the HttpServletResponse interface. Next, let's learn about these methods through API documents.

Let's explain the above functions in Chinese, as shown in the figure below.

1.2.2 common response status codes

Common status codes:

Status codeexplain
200Successful execution
302Like 307, it is a status code for redirection. Only 307 is no longer used
304The requested resource has not changed, use cache.
400Request error. The most common problem is the request parameters
404Requested resource not found
405The request method is not supported
500Server running internal error

First meaning of status code:

Status codeexplain
1xxnews
2xxsuccess
3xxredirect
4xxClient error
5xxServer error

1.3 use examples of response objects

1.3.1 response byte stream output Chinese garbled code

Too much content, please move to another blog:
https://yangyongli.blog.csdn.net/article/details/117877830

1.3.3 response - generate verification code

Too much content, please move to another blog:
https://yangyongli.blog.csdn.net/article/details/117878306

1.3.4 set response message header - control cache

/**
 * Set cache time
 * 	Generally, static cache resources are used
 *  Dynamic resources generally cannot be cached.
 *  At present, we only master Servlet, so we use Servlet for demonstration
 *
 */
public class ResponseDemo4 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String str = "Set cache time";
        /*
         * Setting the cache time is actually setting the response header: Expires, but the value is a millisecond.
         * Using
         * 	response.setDateHeader();
         *
         * Cache for 1 hour is the millisecond value after adding 1 hour to the millisecond of the current time
         */
        response.setDateHeader("Expires",System.currentTimeMillis()+1*60*60*1000);
        response.setContentType("text/html;charset=UTF-8");
        response.getOutputStream().write(str.getBytes());
    }

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

}


1.3.5 set response message header - regular refresh

/**
 * Set response header:
 * Add message headers by periodically refreshing the presentation
 */
public class ResponseDemo5 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String str = "The user name and password do not match. Turn to the login page after 2 seconds...";
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        out.write(str);
        //Scheduled refresh is actually setting a response header
        response.setHeader("Refresh", "2;URL=/login.html");//The time unit set by Refresh is seconds. If you Refresh to another address, you need to splice the address after the time
    }

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

}

1.3.6 request redirection: note that the address bar has changed.

/**
 * Set the response status code to realize redirection
 * Features of redirection:
 * 	 Two requests, address bar change, browser behavior, xxxx
 *
 */
public class ResponseDemo6 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //1. Set the response status code
//		response.setStatus(302);
        //2. Where to direct: in fact, it is to set the response header, Location
//		response.setHeader("Location", "ResponseDemo7");

        //Use redirection method
        response.sendRedirect("ResponseDemo7");//What have you done on this trip? Please look at the above
    }

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

}

Redirected to this

/**
 * Redirected destination
 */
public class ResponseDemo7 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().write("welcome to ResponseDemo7");
    }

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

}

1.3.7 combined application of response and message header - file download

First, create a new directory uploads under the web directory of the project, and copy a picture to the directory, as shown in the following figure:

The Servlet code for file download is as follows:

/**
 * File download
 *
 */
public class ResponseDemo8 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        /*
         * Idea of file download:
         * 		1.Get file path
         * 		2.Read the file into the byte input stream
         * 		3.Tell the browser to open it by downloading (tell the browser to download the MIME type of the file)
         * 		4.Use the byte output stream of the response object to output to the browser
         */
        //1. Get file path (absolute path)
        ServletContext context = this.getServletContext();
        String filePath = context.getRealPath("/uploads/6.jpg");//Obtain the absolute path of the file through the virtual path of the file
        //2. Build a byte input stream through the file path
        InputStream in  = new FileInputStream(filePath);
        //3. Set the response header
        response.setHeader("Content-Type", "application/octet-stream");//Note that when downloading, set the MIME type of the response body and use application / octet stream
        response.setHeader("Content-Disposition", "attachment;filename=1.jpg");//Tell the browser to open by downloading
        //4. Use the byte output stream output of the response object
        OutputStream out = response.getOutputStream();
        int len = 0;
        byte[] by = new byte[1024];
        while((len = in.read(by)) != -1){
            out.write(by, 0, len);
        }
        in.close();
    }

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

}

1.3.8 precautions for response object

First: the character stream and byte stream obtained by response are mutually exclusive, and only one can be selected

Second: the stream obtained by the response does not need to be closed, but can be closed by the server

/**
 * Precautions when using the Response object to obtain the flow:
 * 	1.We can use response to get the stream without closing it. The server will shut us down.
 * 	2.In the response object, byte stream and character stream are mutually exclusive. When outputting, only one can be selected
 *
 */
public class ResponseDemo9 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String str = "test";
        response.getOutputStream().write(str.getBytes());
        //response.getWriter().write(str);
//		response.getOutputStream().write("haha".getBytes());

    }

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

}

Keywords: Python Java Web Development Linux http

Added by davidprogramer on Sun, 30 Jan 2022 11:28:18 +0200