The request has a short life cycle and is only active in one request from the browser to the server. when the request is executed, the current object will be destroyed.
Requests are often used to obtain the table information entered on the browser page-user name, password, and so on. You can also set attribute ("index name", "index value") in servlet ") to store a pair of key-value pairs of the object type. The difference is that the former does not output the output stream information in response, but the latter does. The request object is not destroyed because the jump is still carried out in the same request. Therefore, you can get the value in the key-value pair from the page that jumps.
Java code
/**
* Request Handling Methods in HelloServlet
*/
Protected void service (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, IOException {
Super. service (req, resp );
Resp. setContentType ("text/html; charset = gbk ");
Resp. setCharacterEncoding ("gbk ");
Req. setCharacterEncoding ("gbk ");
// Obtain the parameters entered when the user sends the request
String username = req. getParameter ("username ");
Req. setAttribute ("username", username );
Req. getRequestDispatcher ("redirect. jsp"). forward (req, resp );
// Resp. sendRedirect ("redirect. jsp ");
}
Logon interface: When the login button is clicked, the request is received by the server. The servlet processes the request, saves the username, and jumps to redirect. jsp.
Jump interface: Jump to redirect. jsp, and the user name is displayed on the page. Note that the address bar does not point to redirect. jsp indirectly proves that all operations are in one request.
Firebug: Obviously, the server only receives one post request.
Whether the request lifecycle is in only one request is not verified. If the above operations are completed in two requests, Will username be returned?
Java code
/**
* Request Handling Methods in HelloServlet
*/
Protected void service (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, IOException {
Super. service (req, resp );
Resp. setContentType ("text/html; charset = gbk ");
Resp. setCharacterEncoding ("gbk ");
Req. setCharacterEncoding ("gbk ");
// Obtain the parameters entered when the user sends the request
String username = req. getParameter ("username ");
Req. setAttribute ("username", username );
// Req. getRequestDispatcher ("redirect. jsp"). forward (req, resp );
// Redirect
Resp. sendRedirect ("redirect. jsp ");
}
1. If the user name is displayed as "null", the request lifecycle is one request. 2. The address bar points to redirect. jsp; 3. firebug shows two requests. One is my specified "post", and the other is the default "get ", response Returns the redirected information to the browser, and the browser makes the second request. At this time, the first request object is destroyed, so the information it carries is no longer available.