The main function of Servlet is to process client requests and respond. For this reason, for each request, the web container will create two objects before calling service(), namely HttpServletRequest and HttpServletResponse. Where HttpServletRequest encapsulates HTTP request messages, HttpServletResponse encapsulates HTTP response messages. It should be noted that during the operation of the web server, each Servlet will only create one instance object, but every request will call the service (ServletRequest req, ServletResponse res) method of the Servlet instance. Here HttpServletRequest is a subclass of ServletRequest, and HttpServletResponse is a subclass of ServletResponse.
The inheritance relationship diagram of the HttpServletRequest and HttpServletResponse interface is as follows:
1. HttpServletResponse
The HttpServletResponse interface inherits from the ServletResponse interface. Since HTTP response messages are divided into three parts: status row, response message body, and message body, the HttpServletResponse interface defines a method to send a response status code, response message header, and response message body to the client. Although there are many methods in the HttpServletResponse interface, we only use a few commonly used ones. If you use other methods, you can read the source code or related information of the response.
Send status code related functions
Method description public void setStatus(int sc) sets the status code for the response message. The web server generates a status line with a status code of 200 by default. Public void sendError(int sc) sends a status code indicating the error message. The second method also adds a text message for prompting the description public void sendError(int sc, String msg)
Send response message header related functions
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 add the response header field with the same name, setHeader will override the header field with the same name public void setHeader(String name, String value) public void setContentLength(int len) sets the size of the entity content of the response message, in bytes, that is, sets the value of the Content-Length field public void setContentType(String type) sets the MIME type of the Servlet output content, that is, sets the value of the Content-Type field public void setCharacterEncoding(String charset) sets the output content character encoding, that is, sets the value of the Content-Type field. Note that the priority of this method is higher than that of the setContentType public void sendRedirect(String location) Servlet request redirect
Send response message body related functions
| method | illustrate |
| public ServletOutputStream getOutputStream() | Get the byte output stream of HttpServletResponse ServletOutputStram type |
| public PrintWriter getWriter() | Get the character output stream ServletWriter type of HttpServletResponse |
Chinese output garbled problem
Data in computers are stored in binary form, so when text is transferred, conversion between bytes of characters will occur. The conversion between characters and bytes is completed through a code search table. The process of converting characters into bytes is called encoding, and the process of converting bytes into characters is called decoding. If the code tables used for encoding and decoding are different, garbled code problems will occur.
Note: When encoding the character output stream of the HttpServletResponse object, the default is ISO 8859-1 encoding. This encoding method is incompatible with Chinese. For example, "China" will be encoded as "63 63" (characters that cannot be found in the ISO 8959-1 code table will be displayed 63). When the browser decodes the received data, it will use GB2312 by default, decode "63" to "?", and the browser will decode the two characters "China" to "??".
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 the response message encoding, after commenting "China", the "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 you will encounter the problem of jumping pages regularly. The Refresh header field in HTTP can notify the browser to automatically refresh and jump to other pages within a specified time, and the web page will refresh and jump to the specified page regularly.
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 in 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 specifically used for encapsulated HTTP request messages. Since HTTP request information includes three parts: request line, request header and request body, the HttpServletRequest interface defines related methods for obtaining request line, request header and request body.
Related methods for obtaining request rows
| method | illustrate |
| public String getMethod() | Get HTTP request methods, POST, GET, etc. |
| public String getRequestURI() | Get the resource name part in the request line |
| public String getQueryString() | Get the parameter part in the request line |
| public String getProtocol() | Get the protocol name and version in the request line, such as HTTP 1.1 |
| public String getContextPath() | Get the path belonging to the web application in the request URL |
In fact, the method of request line can be seen from the method name, so I won't post it one by one here.
Related methods for obtaining request message headers
| method | illustrate |
| public String getHeader(String name) | Get the value of the specified field, if no null is returned, if there are multiple returns the first value |
| public Enumeration<String> getHeaders(String name) | Returns an Enumeration collection object with the specified field |
| public Enumeration<String> getHeaderNames() | Returns an Enumeration collection object containing all fields |
| public String getContentType() | Get the value of the Content-Type field |
Print all values of the request header field
package zzz;import java.io.IOException;import java.io.PrintWriter;import java.util.Enumeration;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"); 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); }}Related methods for obtaining the request body
Method Description public ServletInputStream getInputStream() gets the requested ServletInputStream object. If the entity content is non-text, you can only obtain the request body message body through the getInputStream method. The requested BufferedReader getReader() gets the requested BufferedReader object. This object will convert the entity content byte data into a text string encoded by the specified character set.
Get request parameters
| method | illustrate |
| public String getParameter(String name) | Get the specified parameter value, and return null without this parameter |
| public Enumeration<String> getParameterNames() | Returns an Enumeration object containing all parameter names |
| public String[] getParameterValues(String name) | There may be multiple same parameters in the HTTP request to obtain all parameter values corresponding to the same parameter name. |
3. RequestDispatcher interface
When a web resource is requested by the client, if you want the server to notify another resource such as processing a request, in addition to using the function sendRedirect() to implement redirect, it can also be implemented through the instance object of the RequestDispatcher interface. A method to obtain the RequestDispatcher object is defined in the ServletRequest interface - getRequestDispatcher(String path), which returns the RequestDispatcher object of the resource specified by a certain path. The parameter path must start with "/" to represent the root directory of the current web application, that is, the path path must be in this web program, otherwise 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 response |
| public void include(ServletRequest request, ServletResponse response) | Used to include other resources as current response content |
The above is the detailed explanation of Java Web request and response examples introduced by the editor. I hope it will be helpful to everyone!