Wednesday, December 3, 2014

Servlet LifeCycle in Java

Servlet Life Cycle

Consider the following scenario:-

I have written 2 servlet call HelloServlet and HiServlet and one Listener call HelloListener and one Filter call HelloFilter and configured all these component inside web.xml and also configured one context parameter with the name country and value India and also I configured one config parameter for HelloServlet with name city and value Pune and configure one parameter for HiServlet with name email and value sridhar.appani@gmail.com and Hi Servlet configured with <load-on-startup> tag.

After developing application deploy into the web server
1)      Server is started.
2)      I send first request to HelloServelt.
3)      I send to second request to HelloServlet.
4)      I send first request to HiServlet.
5)      Shout down the server.

What will happen in each step inside the container.

1) At the server start-up following task will happen:- 
  1. Web container reads the data from web.xml using sax parse and initialise that data in the main memory.
  2. Container create the server context object and container initialise servet context object with context parameter specification.
  3. Container creates a threadpool.
  4. Container check any servlet is configured with the <load-on-starup> tag. If any servlet is found with <load-on-startup> tag then container initialise that servlet. In the process of initializing servlet container will do following step.
  •  Container loads the servlet class.
  • Container create a servlet instance by calling the default constructor.
  • Container creates one servlet config object and initialize the config object with the config parameter specified.
  • Container initialize config object with servlet context object.
  • Container call init method by passing servletConfig as parameter.
  • Container initialize all the filter configured.
  • All the listener will be initialize.

2) When you send the first request to a servlet which is not initialize at server start up. Following thing will happen:-
  1.  Container collects an incoming request URI and checks any servlet is configured with the same URI. 
  2.  If servlet is not found matching URI then error message will be report to the client.
  3.  if servlet is found with the incoming request URI then it takes servlet name and with the servlet identify servlet class.
  4.  Identified servlet class will be loaded in the memory.
  5.  Servlet instance create by calling the default constructor.
  6.  Servlet config object will be create by container and will be initialize with config parameter.
  7.  Container initialize the servlet config object with servlet context object.
  8.  Container call the init method by passing servletconfig object as parameter.
  9.  Container takes the thread from the thread pool and allocates the request processing.
Thread will do the following task.
a) Servlet request object will be create and will be initialize with request parameter, request header etc.
b) Servlet response object will be create and initialize with response header, output stream etc.
c) Service method call with request and response as parameter.
  
         10. Once service method execution is completed then thread will be return to the pool, request and response object will be destroyed and response stream will be flushed to the client.3) When you send a second request to the servlet container do following tasks:- 
  •  Above 9 and 10 point will happen.
 4) When you send the first request to servlet which initialize at server start up then following tasks will happen:-
  • Above 9 and 10 point will happen.
 5) Server shout down time following tasks will happen 
  •  Thread pool will be destroy.
  •   All the servlet will be destroy. Destroy method will be call on each servlet instance before destroying the instance.
  •  All filter will be destroy. Before destroying filter destroy method will be call by the container.
  • All the listener will be destroy.
  • Container destroy servlet context object.
Servlet Example
Software Requirement:-
1) Jdk 1.6
2) Tomcat 6.0
3) Eclipse
4) MySQL
File Requirement:-
1) index.jsp
2) web.xml 
2) home.jsp
3) LoginServlet.java
4) UserModel.java 
5) JdbcUtil.java

Step by step Procedures:-
1) Right click on Project Explorer select New-->select Dynamic web project.
2) Give Project name set target run time Apache Tomcat v6.0.
3) click on next and then click on finish.
4) create index.jsp file inside webContent as follows.
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<% String error= (String)request.getAttribute("errormsg");
    
    if(error != null) {
%>
<center>
<%= error.toString() %>
</center>
<% } %>
<form action="login.do" method="post">
<center>
<table>
<tr><td>User Name:</td><td><input type="text" name="uname"></td></tr>
<tr><td>Password:</td><td><input type="password" name="password"></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="Login"></td></tr>
</table>
</center>
</form>
</body>
</html>
5) update web.xml file as below:-
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
 <servlet>
      <servlet-name>loginservlet</servlet-name>
      <servlet-class>com.test.LoginServlet</servlet-class>
  </servlet>
    <servlet-mapping>
      <servlet-name>loginservlet</servlet-name>
      <url-pattern>/login.do</url-pattern>
  </servlet-mapping>
      <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>
6) create LoginServlet class is as follow:-

LoginServlet.java
package com.test;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet{   
       private static final long serialVersionUID = 1L;
    public void service(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException{
       // Collect the request parameter
        String username = request.getParameter("uname");
        String password = request.getParameter("password");
       
        // call the Model.
        int x = UserModel.verifyUser(username,password);
        //forwarding.
        RequestDispatcher rd = null;
       
        if(x == 1)
        {
            request.setAttribute("username", username);
            request.setAttribute("password", password);
            rd = request.getRequestDispatcher("/home.jsp");
        }
        else
        {
            String msg = "Invalid Username and Password";
            request.setAttribute("errormsg", msg);
            rd = request.getRequestDispatcher("/index.jsp");
        }
        try
        {
            rd.forward(request, response);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }    
    }
}
7) create UserModel class is as follow:-
UserModel.java
package com.test ;
import java.sql.*;
public class UserModel {
    
    public static int verifyUser(String username, String password)
    {
       Connection con = JdbcUtil.getConnection();
        int x = 0;
        try
        {
            Statement st = null;
            ResultSet rs = null;
            st = con.createStatement();
        
        String query ="select * from login where username='"+username+"' and password='"+password+"'";
        rs = st.executeQuery(query);
        
        if(rs.next())
        {
            x=1;
        }
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return x;
    }
}
8) create JdbcUtil class is as follow:-
JdbcUtil.java
package com.test ;
import java.sql.*;
public class JdbcUtil {
    
    public static Connection getConnection()
    {
        Connection con = null;
        try
        {
           
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/TestDatabase", "root", "kano");
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return con;
    }
}
7) create home.jsp file is as follow:-
home.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<% String username = (String)request.getAttribute("username");
String password = (String)request.getAttribute("password");
%>
Your UserName is:- <%= username %><br/>
Your Password is:- <%= password %>
</body>
</html>
9) import MySQL jar file.
10) run the project.
11) create database is as follow.
       Create database TestDatabase; 
12) create table is as follow.
      Create table login(username varchar(10),password varchar(20));
13) Insert value into table;
      Insert into login values("test","test");



1 comment:

  1. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in Product prototyping during this lockdown period everyone can use it wisely.
    icp-cat training

    ReplyDelete

Java 9 and Java11 and Java17, Java 21 Features

 Java 9 and Java11 and Java17 features along with explanation and examples in realtime scenarios Here's a detailed breakdown of Java 9, ...