@[TOC]
1 Response Object
1.1 Overview of Response Objects
1.1.1 About The Response
Response, which indicates that the server has received the request and has completed processing, and informs the user of the result of processing. Simply put, it means that the server informs the client of the result of the request. In the B/S architecture, the response is to bring the result back to the browser.
The response object, as its name implies, is the object used to implement the above functions in the JavaWeb project.
1.1.2 Common Response Objects
The response object is also defined in the Servlet specification and includes both protocol-independent and protocol-dependent.
-
The protocol independent object standard is the ServletResponse interface
-
The protocol-related object standard is the HttpServletResponse interface
The class structure diagram is as follows:
The response objects described below are all RELATED to the HTTP protocol. The implementation class for the HttpServletResponse interface is used.
Some of you might wonder if, when using a Servlet, you need to define a class that implements the Servlet interface (or inherits its implementation class). Now that we want to implement the response function, should we define a class that implements the HttpServletResponse interface?
The answer to that question is no, we don’t have to. We only need to use it directly in our own Servlet, because the implementation class of this object is provided by Tomcat and we do not need to customize it. It will also help us create the object and pass it into the doGet and doPost methods.
1.2 Common methods
1.2.1 API is introduced
Javaee.github. IO /javaee-spec…
There are a number of methods provided in the HttpServletResponse interface, and we’ll look at them through the API documentation.
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 code | instructions |
---|---|
200 | Execute successfully |
302 | It’s the same status code used for redirection as 307. But 307 is no longer in use |
304 | Requested resource unchanged, using cache. |
400 | Request error. The most common is a problem with the request parameters |
404 | Requested resource not found |
405 | Requested mode not supported |
500 | Server running internal error |
First meaning of status code:
Status code | instructions |
---|---|
1xx | The message |
2xx | successful |
3xx | redirect |
4xx | Client error |
5xx | Server error |
1.3 Example of using response Objects
1.3.1 Response byte stream Output Chinese garbled characters Problem
Too much content, please move my another blog: yangyongli.blog.csdn.net/article/det…
1.3.3 Response – Generates a verification code
Too much content, please move my another blog: yangyongli.blog.csdn.net/article/det…
1.3.4 Setting response Headers — Controls caching
/** * Set the cache time * the cache is usually static resources * dynamic resources can not be cached. * We only know servlets so far, so use servlets as a demo * */
public class ResponseDemo4 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String str = "Set cache time";
/* * Sets the response header: Expires, but the value is a millisecond. * Response.setDateheader (); * * Caches for 1 hour, which is the number of milliseconds at the current time plus the value of milliseconds after 1 hour */
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); }}Copy the code
1.3.5 Setting response Headers — Refresh periodically
/** * Set the response header: * Add the header with a timed refresh demo */
public class ResponseDemo5 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String str = "User name and password do not match, 2 seconds later redirected to login page...";
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.write(str);
// Set a response header
response.setHeader("Refresh"."2; URL=/login.html");//Refresh Sets the time in seconds. If the time is refreshed to another address, the address must be concatenated after the time
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { doGet(request, response); }}Copy the code
1.3.6 Request Redirection: Notice that the address bar is changed.
/** ** Sets the response status code to implement redirection * Redirection features: * two requests, address bar changes, 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 go: set the response header, Location
// response.setHeader("Location", "ResponseDemo7");
// Use the redirection method
response.sendRedirect("ResponseDemo7");// What did you do during your visit
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { doGet(request, response); }}Copy the code
I redirected it here
/** * redirection 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); }}Copy the code
1.3.7 Response and Header combination application – file download
First, create a new directory, Uploads, under the project web directory, and copy an image to the directory, as shown below:
The Servlet code for the file download is as follows:
/** * File download ** /
public class ResponseDemo8 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/* * File download thread: * 1. Obtain the file path * 2. Read the file into byte input stream * 3. Tell the browser to open it as a download (tell the browser the MIME type of the file to download) * 4. Output to the browser using the byte output stream of the response object */
//1. Obtain the file path (absolute path)
ServletContext context = this.getServletContext();
String filePath = context.getRealPath("/uploads/6.jpg");// Obtain the absolute file path from the virtual file path
//2. Build a byte input stream from the file path
InputStream in = new FileInputStream(filePath);
//3. Set the response header
response.setHeader("Content-Type"."application/octet-stream");// When downloading, set the MIME type of the response body with application/octet-stream
response.setHeader("Content-Disposition"."attachment; filename=1.jpg");// Tell the browser to open as a download
//4. Output using the byte output stream 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); }}Copy the code
1.3.8 Precautions for Response Objects
First: The character stream and byte stream generated by response are mutually exclusive, and only one of them can be selected
Second: The stream obtained by Response does not need to be closed, but can be closed by the server
/** ** ** /** ** /** * The stream we get using Response doesn't have to be closed. The server will shut us down. * 2. In the Response object, byte stream and character stream are mutually exclusive, and only one * */ can be selected when output
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); }}Copy the code