[go: up one dir, main page]

0% found this document useful (0 votes)
19 views14 pages

Servlet Life Cycle

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views14 pages

Servlet Life Cycle

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Java Servlet Architecture

 The software architecture of a servlet as the life cycle of the Java


Servlet.
 To write a Servlet, the user needs first to implement the Servlet
Interface, directly or indirectly, using the following import
command.
import javax.servlet.*;
Once the Servlet interface is imported, and we inherit the HTTP
Class, we begin with the Java Servlet's life cycle.
Java 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

not respond to any of the user's commands.


The init() method Syntax:
public void init() throws ServletException
{
//init() method initializing
}
2. service()
The service() method is the heart of the life cycle of a Java Servlet. Right after
the Servlet's initialization, it encounters the service requests from the client
end.
The client may request various services like:
•GET
•PUT
•UPDATE
•DELETE
The service() method takes responsibility to check the type of request received
from the client and respond accordingly by generating a new thread or a set of
threads per the requirement and implementing the operation through the
following methods.
doGet() for GET
doPut() for PUT
doUpdate() for UPDATE
doDelete() for DELETE

The service() method Syntax:


public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
}
3. destroy()
Like the init() method, the destroy() method is also called only
once in the Java Servlet's entire life cycle.
When the destroy() method is called, the Servlet performs the
cleanup activities like,
Halting the current or background threads
Making a recovery list of any related data like cookies to Disk.
After that, the Servlet is badged, ready for the Garbage collector to
have it cleared.
The destroy() method Syntax:
public void destroy() {
//destroy() method finalizing
}
import java.io.*;
import javax.servlet.*;
public class GenericServletLifeCycleDemo extends GenericServlet
{
String msg="";
public void init() throws ServletException
{
msg="Servlet has been Initialized...";
}
public void service(ServletRequest req, ServletResponse res) throws
ServletException, public void destroy()
IOException {
{ System.out.println("Servlet has been
res.setContentType("text/html"); Destroyed...");
PrintWriter out = res.getWriter(); }
out.println(msg); }
out.println("</br> Servlet Life Cycle Has three stages ");
out.println("</br> 1. Initialization ");
out.println("</br> 2. Service ");
out.println("</br> 3. Destroy");
out.println("</br> Servlet started servicing...");
}
Generic Servlet:
Generic Servlet is protocol independent(i.e)it can handle
all types of protocols like http, ftp, smtp etc.
GenericServlet class is direct subclass of Servlet Interface.
GenericServlet is an abstract class
which implements Servlet, ServletConfig and
java.io.Serializable interfaces.
GenericServlet belongs to javax.servlet package.
Generic Servlet supports only service() method.
Extending class must override public abstract void
service(ServletRequest req,ServletResponse res
) method.
GenericServlet implements ServletConfig interface and
provides way to accept initialization parameter passed to
Servlet from web.xml e.g. by using getInitParamter().
import java.io.*;
import javax.servlet.*;

public class GenericServletExample extends GenericServlet


{
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html>");
out.print("<body>");
out.print("<h2>Generic Servlet Example!!!</h2>");
out.print("</body>");
out.print("</html>");
}
}
HttpServlet Class:
HttpServlet is protocol dependent. It supports only http protocol.
HttpServlet class is the direct subclass of Generic Servlet.
HttpServlet is an abstract class which extends GenericServlet and
implements java.io.Serializable interface.
HttpServlet belongs to javax.servlet.http package.
HttpServlet overrides service() method of Generic Servlet and
provides callback on doXXX(HttpServletRequest request,
HttpServletResponse) method whenever it receives HTTP request,
it supports doGet(), doPost(), doPut(), doDelete(), doHead(),
doTrace(), doOptions() methods.
HttpServlet has two service methods public void
service(ServletRequest req,ServletResponse res ) and protected
void service(HttpServletRequest req,HttpServletResponse
res) All the request first goes to the public service() method, which
wrap into Http Objects and calls protected service() method
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 HttpServletExample extends HttpServlet{

public void doGet(HttpServletRequest req, HttpServletResponse


res) throws IOException
{
PrintWriter out = res.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h2>Http Servlet Example!!!</h2>");
out.println("</body>");
out.println("</html>");
}
}
3b) Develop a Servlet program to access Init parameter values form web.xml to
Servlet program by usingServletConfiginterface.

When the Web Container initializes a servlet, it creates


a ServletConfig object for the servlet.
ServletConfig object is used to pass information to a servlet during
initialization by getting configuration information from web.xml(Deployment
Descriptor).

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.*;

public class MyServletConfig extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse


response)throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
ServletConfig sc = getServletConfig();
out.println(sc.getInitParameter(“branch"));
}
}
<web-app>

<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:

Servlet: Methods of RequestDispatcher


RequestDispatcher interface provides two important methods

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

You might also like