In this article, we will focus on two aspects: servlet lifecycle and Servlet Request forwarding. In fact, we have already roughly introduced the entire servlet lifecycle process, but we have not systematically mentioned it. In this article, we will systematically explain it.
Servlet Lifecycle
Servlet runs in the servlet container, and its lifecycle is managed by the container. The servlet lifecycle is represented by the init (), service (), and destroy () methods in the javax. servlet. servlet interface. The servlet lifecycle includes the following four stages:
(1) Loading and instantiation
The servlet container is responsible for loading and instantiating servlet. Create a servlet instance when the servlet container is started or when the container detects that the servlet is needed to respond to the first request. After the servlet container is started, it must know the location of the required servlet class, the servlet container can load the servlet class from the local file system, remote file system, or other network services through the Class Loader. After the servlet class is loaded successfully, the container creates the servlet instance. The container creates a servlet instance through the Java reflection API and calls the default servlet Constructor (that is, the constructor without parameters). Therefore, when compiling the servlet class, A constructor with parameters should not be provided.
(2) initialization
After the servlet is instantiated, the container will call the servlet Init () method to initialize this object. The purpose of initialization is to allow servlet objects to complete initialization before processing client requests, such as establishing database connections and obtaining configuration information. For each servlet instance, the init () method is called only once. During initialization, the servlet instance can use the servletconfig object prepared by the container for it to obtain the initialization parameter information from the Web application configuration information (configured in Web. XML. During initialization, if an error occurs, the servlet instance can throw a servletexception exception or unavailableexception exception to notify the container. A servletexception exception is used to indicate a general initialization failure. For example, the initialization parameter is not found. An unavailableexception exception is used to notify the container that the servlet instance is unavailable. For example, if the database server is not started and the database connection cannot be established, the servlet can throw an unavailableexception to indicate to the container that it is temporarily or permanently unavailable.
(3) Request Processing
The servlet container calls the servlet Service () method to process the request. Note that the init () method must be successfully executed before the service () method is called. In the service () method, the servlet instance obtains the client-side information and request information through the servletrequest object. After processing the request, it calls the method of the servletresponse object to set the response information. During service () method execution, if an error occurs, the servlet instance can throw a servletexception exception or unavailableexception exception. If an unavailableexception indicates that the instance is permanently unavailable, the servlet container will call the destroy () method of the instance to release the instance. Any request to this instance will receive the HTTP
404 (requested resource unavailable) response. If the unavailableexception exception indicates that the instance is temporarily unavailable, any requests to the instance within the time range temporarily unavailable will receive the HTTP 503 sent by the container (the server is temporarily busy, cannot process the request) response.
(4) Service Termination
When the container detects that a servlet instance should be removed from the service, the container will call the destroy () method of the Instance so that the instance can release its resources, save the data to the persistent storage device. When the memory needs to be released or the container is closed, the container will call the destroy () method of the servlet instance. After the destroy () method is called, the container releases the servlet instance and the instance is recycled by the Java garbage collector. If you need this servlet to process the request again, the servlet container will create a new servlet instance.
During the entire servlet lifecycle, The init () and destroy () methods for creating the servlet instance, calling the instance are only performed once. After the initialization is complete, the servlet container saves the instance in the memory and calls its service () method to serve the received request. The following shows the UML sequence diagram of the entire servlet lifecycle, as shown in 1.
Figure 1 UML sequence diagram of servlet Lifecycle
If you want the servlet container to load the servlet at startup, you can configure the <load-on-startup> element in the web. xml file. The configuration method is described in detail later.
Request forwarding
In daily life, the 110 Alarm center receives alarm calls from the masses and submits the alarm request to different police stations for Handling Based on the alarm content (ALARM location and emergency degree. Here, the 110 Alarm Center acts as a dispatcher who forwards various alarm requests to the actual processing unit. The benefits of this processing model are:
1) provides people with a unified Alarm Method (call 110 ).
2) The alarm center can reasonably dispatch resources based on the location of the reporter, the geographical location and Personnel Status of the police station, and arrange the nearest police station to issue police in a timely manner.
3) The alarm center does not process specific cases, which shortens the response time to the alarm request.
In Web applications, this processing model is also widely used. The scheduler role is usually played by Servlet. Such a servlet is called controller ). In the controller, You can forward a request (Request Dispatching) to another servlet or JSP page, or even a static html page, and then process it and generate a response to the request. To complete request forwarding, you must use the javax. servlet. requestdispatcher interface.
Requestdispatcher Interface
The requestdispatcher object is created by the servlet container to encapsulate a server resource identified by the path. The requestdispatcher object can be used to forward requests to other servlet or JSP pages. Two methods are defined in the requestdispatcher interface.
public void forward(ServletRequest request, ServletResponse response) throws ServletException, java.io.IOException
This method is used to pass requests from a servlet to another servlet, JSP page, or HTML file on the server. In servlet, you can make a preliminary processing of the request, and then call this method to pass the request to other resources to output the response. Note that this method must be called before the response is submitted to the client. Otherwise, it will throw an illegalstateexception. After the forward () method is called, The unsubmitted content in the response cache will be cleared automatically.
public void include(ServletRequest request, ServletResponse response) throws ServletException, java.io.IOException
This method is used to include the content of other resources (servlet, JSP page, or HTML file) in the response. The difference between the forward () method and the forward () method is that the include () method is used to forward requests to other servlets. The called Servlet's response to this request will be incorporated into the original response object, the original servlet can continue to output response information. The forward () method is used to forward requests to other servlets. The called servlet is responsible for responding to the requests, and the execution of the original servlet is terminated.
Obtain the requestdispatcher object
There are three methods to obtain the requestdispatcher object. First, use the getrequestdispatcher () method in the servletrequest interface:
public RequestDispatcher getRequestDispatcher(java.lang.String path)
The other two methods use the getnameddispatcher () and getrequestdispatcher () methods in the servletcontext interface:
public RequestDispatcher getRequestDispatcher(java.lang.String path)public RequestDispatcher getNamedDispatcher(java.lang.String name)
We can see that the servletrequest interface and the servletcontext interface each provide a getrequestdispatcher () method with the same name. What is the difference between the two methods?
The parameters of the two getrequestdispatcher () methods are the path names of resources. However, the parameters of the getrequestdispatcher () method in the servletcontext interface must start with a slash, it is interpreted as the path relative to the current context root. For example,/myservlet is a valid path, and .. /myservlet is an invalid path. The parameters of the getrequestdispatcher () method in the servletrequest interface can be not only the path relative to the context root, but also the path relative to the current servlet. For example,/myservlet and myservlet are both valid paths. If the path starts with a slash (/), it is interpreted as the path relative to the current context root; if the path does not start with a slash (/) is interpreted as the path relative to the current servlet. The getnameddispatcher () method in the servletcontext interface takes the servlet (or JSP page) Name given in the deployment descriptor as the parameter.
Call the getcontext () method of the servletcontext object to obtain the context object of another web application. Use this context object to call the requestdispatcher () method to obtain the requestdispatcher object, you can forward requests to resources in another web application. However, to access resources across web applications, you must set the crosscontext attribute to true in the <context> element of the current web application.
An instance for request forwarding
Let's continue to look at an example. We compile a portalservlet. this servlet first checks whether the user has logged on. If not, it calls the include () method of the requestdispatcher interface, forward the request to loginservlet. loginservlet sends a logon form in the response. If the user has logged on, call the forward () method of the requestdispatcher interface to forward the request to welcomeservlet, displays the response information to the user. Like the previous article, we still write programs in the mydemo web project. The following is the code of portalservlet:
Package COM. shan. web; import Java. io. *; import javax. servlet. *; import javax. servlet. HTTP. *; public class portalservlet extends httpservlet {public void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {response. setcontenttype ("text/html; charset = UTF-8"); printwriter out = response. getwriter (); out. println ("<HTML>
In the doget () method, first determine the user name and password. If the user name and password exist, use the getrequestdispatcher () method of the context object to obtain the requestdispatcher object. The input path parameter must start with a slash, then forward the request to welcome using the forward () method. do servlet processing. (Note: After the forward () method is called, the HTML code output will be cleared automatically, and the control of execution will be handed over to welcome, in doget () the remaining code in the method is not executed .)
If the user does not log on or has entered an incorrect user name or password, the requestdispatcher object is obtained using the getrequestdispatcher () method of the request object. The input path parameter does not start with a slash, indicates the path relative to the current servlet, and then calls the include () method to forward the request to login. do this servlet processing, when login. after do finishes processing the request, it returns control to portalservlet and continues the code after execution.
The loginservlet code is as follows:
Package COM. shan. web; import Java. io. *; import javax. servlet. *; import javax. servlet. HTTP. *; public class loginservlet extends httpservlet {public void doget (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {response. setcontenttype ("text/html; charset = gb2312"); printwriter out = response. getwriter (); out. println ("<form method = post action = portal. DO> "); out. println ("<Table>"); out. println ("<tr>"); out. println ("<TD> enter the User name: </TD>"); out. println ("<TD> <input type = text name = username> </TD>"); out. println ("</tr>"); out. println ("<tr>"); out. println ("<TD> enter password: </TD>"); out. println ("<TD> <input type = password name = passwd> </TD>"); out. println ("</tr>"); out. println ("<tr>"); out. println ("<TD> <input type = reset value = refill> </TD>"); out. println ("<TD> <input type = submit value = logon> </TD>"); out. println ("</tr>"); out. println ("</table>"); out. println ("</form>");} public void dopost (httpservletrequest request, httpservletresponse response) throws servletexception, ioexception {doget (request, response );}}
The <HTML>, We also need to write a welcomeservlet program, the Code is as follows:
package com.shan.web;import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class WelcomeServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {response.setContentType("text/html;charset=gb2312"); PrintWriter out=response.getWriter();String username=request.getParameter("username");String welcomeInfo="Hello, "+ username;out.println("
The program is simple, that is, retrieve the username and output it.
After the program is compiled, We need to compile the program, win + R, input cmd, and switch to the project directory. Enter the following statements one by one:
javac -classpath D:\apache-tomcat-7.0.33\lib\servlet-api.jar -d classes src\com\shan\web\PortalServlet.java
javac -classpath D:\apache-tomcat-7.0.33\lib\servlet-api.jar -d classes src\com\shan\web\LoginServlet.java
javac -classpath D:\apache-tomcat-7.0.33\lib\servlet-api.jar -d classes src\com\shan\web\WelcomeServlet.java
After compilation. copy the class file to the corresponding directory in the WEB-INF folder under the D: \ apache-Tomcat-7.0.33 \ webapps \ mydemo directory (that is, in the classes \ com \ Shan \ Web Folder ). Edit the Web. xml file. The modification is as follows:
<?xml version='1.0' encoding='utf-8'?><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0" metadata-complete="true"> <description> My Demo. </description><servlet><servlet-name>selectServlet</servlet-name><servlet-class>com.shan.web.MyDemoServlet</servlet-class></servlet><servlet><servlet-name>countServlet</servlet-name><servlet-class>com.shan.web.CounterServlet</servlet-class></servlet><servlet><servlet-name>PortalServlet</servlet-name><servlet-class>com.shan.web.PortalServlet</servlet-class></servlet><servlet><servlet-name>LoginServlet</servlet-name><servlet-class>com.shan.web.LoginServlet</servlet-class></servlet><servlet><servlet-name>WelcomeServlet</servlet-name><servlet-class>com.shan.web.WelcomeServlet</servlet-class></servlet><servlet-mapping><servlet-name>selectServlet</servlet-name><url-pattern>/SelectColor.do</url-pattern></servlet-mapping><servlet-mapping><servlet-name>countServlet</servlet-name><url-pattern>/count.do</url-pattern></servlet-mapping><servlet-mapping><servlet-name>PortalServlet</servlet-name><url-pattern>/portal.do</url-pattern></servlet-mapping><servlet-mapping><servlet-name>LoginServlet</servlet-name><url-pattern>/login.do</url-pattern></servlet-mapping><servlet-mapping><servlet-name>WelcomeServlet</servlet-name><url-pattern>/welcome.do</url-pattern></servlet-mapping></web-app>
Enter http: // localhost: 8080/mydemo/portal. Do in the browser, and enter the username and password (Shan and 1234) to view the welcome information hello and Shan.
Differences between sendredirect () and forward () Methods
The sendredirect () method of the httpservletresponse interface and the forward () method of the requestdispatcher interface can use other resources (servlet, JSP page, or htlm file) to serve the client, however, these two methods are essentially different. The working principles of the sendredirectt () method and the forward () method are given below.
The working principle/interaction process of the sendredirect () method is as follows:
1) the browser accesses servlet1.
2) servlet1 wants servlet2 to serve the client.
3) servlet1 calls the sendredirect () method to redirect client requests to servlet2.
4) the browser accesses servlet2.
5) servlet2 responds to client requests.
From the interaction process above, we can see that calling the sendredirect () method actually tells the browser the location of servlet2 and allows the browser to re-access servlet2. Call the sendredirect () method to set the location response header in the response. It should be noted that this process is transparent to users and the browser will automatically complete new access. The URL displayed in the URL bar of the browser is the URL after redirection.
The working principle/interaction process of the Forward () method is as follows:
1) the browser accesses servlet1.
2) If servlet1 wants servlet2 to respond to the client's request, it calls the forward () method and forwards the request to servlet2 for processing.
3) servlet2 responds to the request.
From the interaction process above, we can see that calling the forward () method is transparent to the browser, and the browser does not know that the servlet serving the browser has been changed to servlet2, it only knows that a request is sent and a response is obtained. The URL displayed in the browser URL bar is always the original request URL.
There is another difference between the sendredirect () method and the forward () method, that is, the sendredirect () method can not only redirect between different Web applications located on the same host, in addition, the client can be redirected to Web application resources on other servers.
Reprinted please indicate the source: http://blog.csdn.net/iAm333