The main function of the servlet is to process the client request and respond, for each request, the Web container creates two objects before the service () is invoked, respectively, HttpServletRequest and HttpServletResponse. where HttpServletRequest encapsulates HTTP request messages, HttpServletResponse encapsulates HTTP response messages. It should be noted that each servlet creates only one instance object during the Web server run, but each request invokes the service (ServletRequest req, Servletresponse Res) method of the servlet instance. Here HttpServletRequest is a subclass of ServletRequest, HttpServletResponse is a subclass of Servletresponse.
The HttpServletRequest and HttpServletResponse interface inheritance diagrams are as follows:
1, HttpServletResponse
The HttpServletResponse interface inherits from the Servletresponse interface, because the HTTP response message is divided into the status row, the response message body, the message body three parts, A method for sending a response status code to a client, responding to a message header, and responding to a message body is defined in the HttpServletResponse interface. Although there are many methods in the HttpServletResponse interface, but we often use a few, if the other method can be read the response of the source code or related information on the line.
Send Status Code correlation function
Method |
Description |
public void SetStatus (int sc) |
Sets the response message status code, and the Web server defaults to a status line with a status code of 200 |
public void Senderror (int sc) |
Sends a status code that represents the error message, and the second method adds a text message for the hint description |
public void Senderror (int sc, String msg) |
Send Response message header correlation function
Method |
Description |
public void AddHeader (string name, String value) |
Sets the HTTP response header field, name specifies the field name, and value specifies the field value. AddHeader can increase the response header field with the same name, SetHeader will overwrite the header field with the same name |
public void SetHeader (string name, String value) |
public void setcontentlength (int len) |
Sets the size, in bytes, of the entity content of the response message, which sets the value of the Content-length field |
public void setContentType (String type) |
Sets the MIME type of the servlet output, which sets the value of the Content-type field |
public void setcharacterencoding (String charset) |
Set the output character encoding, that is, to set the value of the Content-type field, note that the method has a higher precedence than the setContentType |
public void Sendredirect (String location) |
Servlet Request Redirection |
Send Response message body correlation function
Method |
Description |
Public Servletoutputstream Getoutputstream () |
Gets the httpservletresponse byte output stream Servletoutputstram type |
Public PrintWriter getwriter () |
Gets the character output stream servletwriter type of the HttpServletResponse |
Chinese output garbled problem
The data in the computer is stored in binary form, so that when the text is transferred, the conversion between the bytes of the character occurs. The conversion between characters and bytes is done through the Code table, the process of converting characters into bytes is called encoding, and the process of converting bytes to characters is called decoding, and if the Code table used for encoding and decoding is different, garbled problems will occur.
Note: The HttpServletResponse object's character output stream is encoded with the ISO 8859-1 encoding, which is not compatible with Chinese, for example, "China" is encoded as "63 63" (characters that are not found in the ISO 8959-1 Code table show 63). When the browser to the received data decoding, will default to use GB2312, "63" decoded to "?", the browser will "China" two characters decoded as "??".
HttpServletResponse Program Example
Package zzz;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
public class Hello extends HttpServlet {
@Override public
void doget (HttpServletRequest request, HttpServletResponse response) throws IOException {
//Set Response message encoding, after comment "China" will show "??" Garbled
Response.setcontenttype ("Text/html;charset=utf-8");
PrintWriter out = Response.getwriter ();
Out.println ("Hello China");
}
@Override public
void DoPost (HttpServletRequest request, httpservletresponse response) throws IOException {
This.doget (request, response);
}
Sometimes encountered the problem of a scheduled Jump page, http in the Refresh header field can inform the browser in a specified time to automatically refresh and jump to other pages, the Web page timed refresh and jump to the specified page.
Package zzz;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
public class Hello extends HttpServlet {
@Override public
void doget (HttpServletRequest request, HttpServletResponse response) throws IOException {
//Set Response message encoding
response.setcontenttype ("text/html;charset= Utf-8 ");
Response.setheader ("Refresh", "2;url=http://www.baidu.com");
PrintWriter out = Response.getwriter ();
Out.println ("Hello China, jump to Baidu after 2 seconds");
}
@Override public
void DoPost (HttpServletRequest request, httpservletresponse response) throws IOException {
This.doget (request, response);
}
2, HttpServletRequest
The HttpServletRequest interface inherits the ServletRequest interface and is used specifically for marshaling HTTP request messages. Since the HTTP request information includes the request line, the request header, and the request body, the HttpServletRequest interface defines the relevant methods for obtaining the request line, the request header, and the request body.
Get the related method of the request line
Method |
Description |
Public String GetMethod () |
Gets the HTTP request method, POST, get, and so on |
Public String Getrequesturi () |
Gets the resource name portion of the request line |
Public String getquerystring () |
Gets the parameters section in the request line |
Public String Getprotocol () |
Gets the protocol name and version in the request line, such as HTTP 1.1 |
Public String Getcontextpath () |
Gets the path that belongs to the Web application in the request URL |
In fact, the method of requesting the line from the method name can see its role, here is not one of them posted.
How to get the request message headers
Method |
Description |
public string GetHeader (string name) |
Gets the value of the specified field, if no null is returned, if multiple returns the first value |
Public enumeration<string> getheaders (String name) |
Returns a enumeration collection object for a specified field |
Public enumeration<string> Getheadernames () |
Returns a enumeration collection object that contains all the fields |
Public String getContentType () |
Get the value of the Content-type field |
Print all values for the request message header field
package zzz; import java.io.IOException; import java.io.PrintWriter; Import java.util.En
Umeration;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse; public class Hello extends HttpServlet {@Override public void doget (HttpServletRequest request, HttpServletResponse R
Esponse) throws IOException {//Set Response message encoding Response.setcontenttype ("Text/html;charset=utf-8");
PrintWriter out = Response.getwriter ();
enumeration<string> names = Request.getheadernames ();
while (Names.hasmoreelements ()) {String name = Names.nextelement ();
String value = Request.getheader (name);
OUT.PRINTLN (name + ":" + value + "</br>");
@Override public void DoPost (HttpServletRequest request, httpservletresponse response) throws IOException {
This.doget (request, response); }
}
How to get the request body
Method |
Description |
Public ServletInputStream getInputStream () |
Gets the requested ServletInputStream object, if the entity content is not text, can only get the request body message body through the getInputStream method |
Public BufferedReader Getreader () |
Gets the requested BufferedReader object that converts entity content byte data to a text string of the specified character set encoding |
GET Request Parameters
Method |
Description |
public string GetParameter (string name) |
Gets the specified parameter value without the parameter returning NULL |
Public enumeration<string> Getparameternames () |
Returns a enumeration object that contains all the parameter names |
Public string[] Getparametervalues (String name) |
There may be multiple identical parameters in the HTTP request, getting all parameter values corresponding to the same parameter name |
3, RequestDispatcher interface
When a Web resource is requested by a client, if you want the server to notify another resource such as processing a request, in addition to implementing redirection using functional Sendredirect (), you can also implement it through an instance object of the RequestDispatcher interface. A method--getrequestdispatcher (String path) that gets the RequestDispatcher object is defined in the ServletRequest interface. It returns the RequestDispatcher object for the resource specified by a path, and the parameter path must begin with "/" to represent the root of the current Web application, that is, the path path must be in this Web program, or an exception will occur.
Methods in RequestDispatcher interface
Method |
Function |
public void forward (ServletRequest request, servletresponse response) |
Pass a servlet to another Web resource and pass the request to another resource for a response |
public void include (ServletRequest request, servletresponse response) |
Used to include other resources in the current response content |
The above is a small series to introduce the Java Web request and response examples of the relevant content, I hope to help you!