Servlet Life Cycle
Servlet Life Cycle
The Java Servlet Life cycle includes three stages right from
its start to the end until the Garbage Collector clears it.
These three stages are described below.
init()
service()
destroy()
1. init()
The init() is the germinating stage of any Java Servlet.
When a URL specific to a particular servlet is triggered, the init() method is
invoked.
With every server starting up, the corresponding servlets also get started,
and so does the init() method.
One important specialty of the init() method is the init() method only gets
invoked once in the entire life cycle of the Servlet, and the init() method will
Methods of ServletConfig
•String getInitParameter(String name):returns a String value
initialized parameter, or NULL if the parameter does not exist.
•Enumeration getInitParameterNames(): returns the names of the
servlet's initialization parameters as an Enumeration of String
objects, or an empty Enumeration if the servlet has no initialization
parameters.
•ServletContext getServletContext(): returns a reference to the
ServletContext
•String getServletName(): returns the name of the servlet instance
<font face="verdana" size="2px">
Index.html
<form action="check" method="post">
Example on ServletConfig<br>
<input type="submit" value=“ClickHere">
</form>
</font>
import java.io.*;
import javax.servlet.*; MyServletConfig.java
import javax.servlet.http.*;
<servlet>
<servlet-name>ServletConfigDemo</servlet-name>
<servlet-class> MyServletConfig </servlet-class>
<init-param>
<param-name>branch</param-name>
<param-value>Computer Science & Engineering</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ServletConfigDemo</servlet-name>
<url-pattern>/check</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
3c) Develop a Servlet program to navigate from one Servlet page to another Servlet
page by using RequestDispatcher interface.
Request Dispatcher in Servlet:
In Java, the RequestDispatcher Interface is used for dispatching the request to a
resource i.e Html, servlet or JSP. The Contents of another resource can be included in
this interface. There are two methods of RequestDispatcher. They are as following:
Methods Description
public void forward(ServletRequest It is used for forwarding the request
request,ServletResponse from one servlet to another servlet
response)throws on a server.
ServletException,java.io.IOException
public void include(ServletRequest It is used for including the content of
request,ServletResponse the resource in the response.
response)throws
ServletException,java.io.IOException