ServletContextEvent and ServletContextListener in Servlet

ServletContextEvent class gives warnings about changes to the servlet connection of a web application.

On the off chance that you need to perform some work right time of sending the web venture, for example, making database association, making every one of the tables of the task and so on, you have to execute ServletContextListener interface and give the usage of its techniques.

Method of ServletContextEvent class

There are one method of ServletContextEvent class in Servlet.

public ServletContext getServletContext():

returns the instance of ServletContext.

Methods of ServletContextListener interface

There are two methods define in the ServletContextListener interface which must be implemented by the servlet programmer.

Methods Description
void contextDestroyed(ServletContextEvent e) is invoked when the application is destroyed.
void contextInitialized(ServletContextEvent e) is invoked when the application is initialized.

And There is only one constructor defined in the ServletContextEvent class.

  1. ServletContextEvent(ServletContext e)

Example

We need create some pages

  1. index.html
  2. MyListener.java
  3. FetchData.java

index.html

<a href="servlet1">fetch records</a>

MyListener .java

import javax.servlet.*;   
import java.sql.*;   
  
public class MyListener implements ServletContextListener{   
public void contextInitialized(ServletContextEvent event) {   
try{   
Class.forName("oracle.jdbc.driver.OracleDriver");   
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");   
         
//storing connection object as an attribute in ServletContext   
ServletContext ctx=event.getServletContext();   
ctx.setAttribute("mycon", con);   
           
}catch(Exception e){e.printStackTrace();}   
}   
  public void contextDestroyed(ServletContextEvent arg0) {}   
}  


FetchData.java

import java.io.*;   
import javax.servlet.*;   
import javax.servlet.http.*;   
import java.sql.*;   
  
public class FetchData extends HttpServlet {   
       
public void doGet(HttpServletRequest request, HttpServletResponse response)   
        throws ServletException, IOException {   
  
response.setContentType("text/html");   
PrintWriter out = response.getWriter();   
       
try{   
//Retrieving connection object from ServletContext object   
ServletContext ctx=getServletContext();   
Connection con=(Connection)ctx.getAttribute("mycon");   
  
PreparedStatement ps=con.prepareStatement("select * from emp32",   
ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);   
               
ResultSet rs=ps.executeQuery();   
while(rs.next()){   
out.print("
"+rs.getString(1)+" "+rs.getString(2));    }                    con.close();    }catch(Exception e){e.printStackTrace();}                out.close();    }    }