Example programs of lifecycle of servlets



A Generic servlet contains the following five methods:

init():

public void init(ServletConfig config) throws ServletException

init() method :This Method is called only once by the servlet container throughout the life of a servlet. By this init() method the servlet get to know that it has been placed into service.

The servlet cannot be put into the service if

*  The init() method does not return within a fix time set by the web server.
*  It throws a ServletException

Parameters
– The init() method takes a ServletConfig object that contains the initialization parameters and servlet’s configuration and throws a ServletException if an exception has occurred.

service() Method:

public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException

Once the servlet starts getting the requests, the service() method is called by the servlet container to respond. The servlet services the client’s request with the help of two objects. These two objects javax.servlet.ServletRequest and  javax.servlet.ServletResponse are passed by the servlet container.

The status code of the response always should be set for a servlet that throws or sends an error.

Parameters -  The service() method takes the ServletRequest object that contains the client’s request and the object ServletResponse contains the servlet’s response. The service() method throws ServletException and IOExceptions exception.

getServletConfig() Method:

public ServletConfig getServletConfig()

This method contains parameters for initialization and startup of the servlet and returns a ServletConfig object. This object is then passed to the init method. When this interface is implemented then it stores the ServletConfig object in order to return it. It is done by the generic class which implements this inetrface.

Returns -  the ServletConfig object

getServletInfo() Method:

public String getServletInfo()

The information about the servlet is returned by this method like version, author etc. This method returns a string which should be in the form of plain text and not any kind of markup.

Returns – a string that contains the information about the servlet

destroy() Method:

public void destroy()

This method is called when we need to close the servlet. That is before removing a servlet instance from service, the servlet container calls the destroy() method. Once the servlet container calls the destroy() method, no service methods will be then called . That is after the exit of all the threads running in the servlet, the destroy() method is called. Hence, the servlet gets a chance to clean up all the resources like memory, threads etc which are being held.

Some Important methods  used in the lifecycle of servlets:

Sample:#1

import java.io.*;
import javax.servlet.*;

public class HelloServlet extends GenericServlet {

public void  init ( ServletConfig  config ) {

super.init ( config );
}
public void  service (
ServletRequest  req, ServletResponse  res )
throws ServletException, IOException {

PrintStream  out = new PrintStream ( res.getOutputStream ( ) );
out.println ( “Hello, World!” );
}
public void  destroy ( ) {

super.destroy ( );
}
}

Sample:#2

The Basic Example of servlet Program

The Login Page of servlet:
<html>
<head>
<title>ADMINSTRATOR LOGIN</title>
</head>
<script language=’javascript’>
var ele_arr=new Array(“Center ID”,”Password”);

function validate()
{
var i=0;
var ele=login.elements.length-2;

var status;
a:for(i=0;i<=ele;i++)
{
if(login.elements[i].value==”")
{
alert(“Sorry!! The ‘”+ele_arr[i]+”‘ field cannot be blank\nPlease enter a value”);
login.elements[i].focus();
status=”NO”;
break a;
}
else
{
status=”YES”;
}
}

if(status==”YES”)
{
return true;
}
else
{
return false;
}
}

</script>

<body background=”images\backgrd.GIF” bgcolor=”#FFCCFF” leftmargin=”0″ rightmargin=”0″>
<FORM action=”/../Login” method=”Get” name=login onsubmit=’return validate();’>

<font color=”#FF0000″ size=”5″ face=”Verdana, Arial, Helvetica, sans-serif”><strong>LOGIN HERE </strong></font><br>

<font color=”#FF00FF” size=”4″>User Name:</font>
<input type=TEXT name=”text1″  >

<font color=”#FF33FF” size=”4″>PASSWORD:</font>
<input type=PASSWORD name=”text2″>

<input type=”submit” name=”Submit1″ value=” L O G I N”>
&nbsp;&nbsp;&nbsp;&nbsp;
<input type=”reset” name=”Submit2″ value=” R E S E T “>

</FORM>
</body>
</html>

Servlet program for the above html page is using the login servlet we are validating the login members

import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.io.*;
public class Login extends HttpServlet
{
Connection con;
public void init()
{
try{
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
con=DriverManager.getConnection(“jdbc:odbc:iams”);
}
catch(ClassNotFoundException e)
{  System.out.println(e);  }
catch(SQLException e)
{ System.out.println(e); }
}
public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
try
{
res.setContentType(“text/html”);
PrintWriter out=res.getWriter();
String log=req.getParameter(“text1″);
String pwd=req.getParameter(“text2″);

PreparedStatement stmt=con.prepareStatement(“select * from login where username=?”);
stmt.setString(1,log);
ResultSet rs=stmt.executeQuery();
if(rs.next())
{
String user=rs.getString(“username”);
String pword=rs.getString(“password”);
if(pword.equals(pwd))
{
HttpSession s1=req.getSession();
s1.setAttribute(“userid”,user);
HttpSession s2=req.getSession();
s2.setAttribute(“password”,pword);
ServletContext ctx=getServletContext();
RequestDispatcher rd=ctx.getRequestDispatcher(“/XXX.html”);
rd.forward(req,res);
}
else
{
ServletContext ctx=this.getServletContext();
RequestDispatcher rd=ctx.getRequestDispatcher(“/AError.html”);
rd.forward(req,res);
}
}
else {
ServletContext ctx=this.getServletContext();
RequestDispatcher rd=ctx.getRequestDispatcher(“/AError.html”);
rd.forward(req,res);
}

}catch(SQLException e)
{  System.out.println(e); }
}

public void destroy()
{
try{
con.close();
} catch(SQLException e)
{ System.out.println(e);  }
}
}

Configure the web.xml for this servlet by using the code:

web.xml (Excerpt illustrating initialization parameters)

<?xml version=”1.0″ encoding=”ISO-8859-1″?>
<!DOCTYPE web-app PUBLIC
“-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN”
“http://java.sun.com/j2ee/dtds/web-app_2_2.dtd”>

<web-app>
<servlet>
<servlet-name>SomeName</servlet-name>
<servlet-class>Login</servlet-class>
/* <init-param>
<param-name>parameter1</param-name>
<param-value>First Parameter Value</param-value>
</init-param>*/

</servlet>
<servlet-mapping>
<servlet-name>SomeName</servlet-name>
<url-pattern>/the action path given in the html action</url-pattern>
<servlet-mapping>
<!– … –>
</web-app>

Random Posts

  • JAVA UTIL PACKAGE
  • What is Thread, How to Use Threads?
  • Can we provide a constructor in the servlet class
  • Deployment Descriptor
  • What is Thread Safe Servlet

Post a Comment