Java Web Summary (IV), Java Web Summary
Use Servlet to send Server Response Information
The Servlet API defines a special interface class javax. servlet. http. HttpServletResponse to create an HTTP response, including the HTTP status line, response header, and message body;
HTTP response example
Set response status line
-The Status line consists of HTTP protocol, status code, and status description.
-The status description is directly related to the status code.
-The HTTP protocol is determined by the server.
-You can set status codes to implement many important functions (you can redirect users to another website and instruct the attached documents to be images, PDF or HTML ......)
HTTP status code:
100-199: indicates information code, indicating other actions that the client should take, and the request is in progress.
200-299: indicates that the customer request is successful.
300-399: indicates the resource file that has been removed and the new address.
400-499: indicates an error caused by the client.
500-599: indicates an error caused by the server.
Set status code
-Use the setStatus () method of HttpServletResponse
// The setStatus method parameter is an integer // use the constant setStatus (HttpServletResponse. SC _NOT_FOUND) in HttpServletResponse );
-Set the status code to return the description.
Response sets the status code to 404.
No file found. The web server returns a 404 response.
HTTP Response Information is composed of status lines, response headers, empty lines, and message bodies (content documents) in order and sent to the browser as a stream.
HTTP Response Information is composed in order and sent to the browser
Tip: The Servlet specification does not specify that the Servlet must cache the message body. Therefore, you must set the status code before using PrintWriter to output the message body. |
HttpServletResponse provides dedicated methods for two common scenarios:
-SendError Method
Public void sendError (int code, String message)
This method generates a 404 response and generates a short HTML error document to the customer.
Response. sendError (404, "path error ");
SendError result
-SendRedirect Method
Public void sendRedirect (String url)
This method generates a 302 response and instructs the URL path of the new document in the Location header (similar to the jump Effect of tag a, two requests and responses are generated ).
Set Response Header
The HTTP header that the HttpServletResponse object uses to manipulate the response
-ContainsHeader (String name): returns a Boolean value indicating whether a specified response header is set.
-SetHeader (String name, String value): set a common response header with a given name and String. If the response header has been set, the new value overwrites the current value. Before setting the value, you can use containsHeader to determine whether the header exists;
-SetIntHeader (String name, int value): Set the response header with a given name and integer value. If the response header has been set, the new value overwrites the current value. Before setting the value, you can use containsHeader to determine whether the header exists;
-SetDateHeader (String name, long date): Set the response header with a given name and date value. The date value here should be a long integer that is precise to milliseconds since January 1, (GMT. If the response header has been set, the new value overwrites the current value. Before setting the value, you can use containsHeader to determine whether the header exists;
-AddHeader (String name, String value): Add a response header with a given name and String value in response, regardless of whether the header with the same name is stored. This method allows the response header to have multiple values.
-AddIntHeader (String name, intvalue): Add a response header with a given name and integer value in response. This method allows the response header to have multiple values.
-AddDateHeader (String name, long value): Add a given name and date value to response to set the response header. The date value here should be a long integer that is precise to milliseconds since January 1, (GMT. This method allows the response header to have multiple values.
-SetContentType (String mimeType): used to set the MIME type of the content returned to the client.
-AddCookie: used to insert a Cookie to set-cookie. Because multiple Set-Cookie rows exist in the HTTP response, there is no corresponding setCookie method.
Purpose: Tell the client
-Type of content sent back
-How much content is being sent
-Type of the server sending content
Set Response Message Body
-The HttpServletResponse object is responsible for returning information to the client.
-The HttpServletResponse object generates only one empty HTTP response.
-The getWriter () or getOutputStream () method must be used to return custom content.
-GetWriter () transfers common text
-GetOutputStream () transfers binary content
Transfer text streams
The getWriter () method is used to obtain an output stream.
PrintWriter out = response. getWriter (); // The same as writing HTML, but the println and print methods are required to spell out. println ("
Transfer binary stream
The getOutputStream () method can control the information sent to the client.
This method returns the javax. servlet. ServletOutputStream object.
ServletOutputStream allows developers to write original bytes.
OutputStream is more efficient than using PrinterWriter to send text
Allows you to dynamically create numeric content of any form
Package com. java. downLoad;
Import java. io. IOException;
Import java. io. InputStream;
Import javax. servlet. ServletContext;
Import javax. servlet. ServletException;
Import javax. servlet. ServletOutputStream;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
/**
* Servlet implementation class DownLaod
*/
Public class DownLaod extends HttpServlet {
Private static final long serialVersionUID = 1L;
Protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DoPost (request, response );
}
Protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Obtain the file name
String filename = request. getParameter ("filename ");
// Set the object MIME type
ServletContext SC = this. getServletContext ();
Response. setContentType (SC. getMimeType (filename ));
// Set Content-Disposition, named as the current time in milliseconds
InputStream fiels = null;
Response. setHeader ("Content-Disposition", "attachment; filename =" + System. currentTimeMillis ());
// Get the file and convert it to a stream
Fiels = SC. getResourceAsStream ("/downLoad/" + filename );
// Transfer Stream
ServletOutputStream out = response. getOutputStream ();
Byte [] buf = new byte [1, 1024];
Int length = 0;
While (length = fiels. read (buf ))! =-1 ){
Out. write (buf, 0, length );
}
// Close the stream
If (out! = Null ){
Out. close ();
Out. flush ();
}
If (fiels! = Null ){
Fiels. close ();
}
}
}
Set Request redirection
-You can select another server program to process requests.
-Redirect requests to a completely different URL
Redirection Principle
The browser sends an HTTP request
Servlet sends the 302 response code and Location response hair to the client and the browser.
The browser resends the HTTP request based on the new URL in the Location header.
Set automatic refresh and wait page
-Automatically refresh the current page or a new page within the specified time
-Control response based on time
-You want to suspend a short period of time in the response.
Response. setHeader ("Refresh", "time; URL = url ");