Connect to Database Using ServletContextListener Interface

This article explains connecting to a database using ServletContextListener. We should however first know why we need ServletContextListener.
 

ServletContextListener

 
You know that the context parameter in a XML Deployment Descriptor can only be written in a string. You cannot pass an object in the Deployment Descriptor. So if you pass the database URL , username and password in the Deployment Descriptor then it will be converted into a database reference that can be used by another part of the web application. This is done by ServletContextListener.
 
We will be needing three classes and one Deployment Descriptor file to perform this operation.
 
So, first we create a dynamic project in Eclipse using the following path: "File" -> "New" -> "Dynamic Web Project".
 
ServletContextListener 
 
Give the project whatever name you choose to and click on "Next". On the final window don't forget to check the "Generate web.xml" check box to create the XML Deployment Descriptor.
 
ServletContextListener 
 
Now we need to write the context parameters in the XML file and the listener class to tell the container about it. So in the WebContent folder click on the WEB-INF folder and click on the web.xml file and write these parameters and the listener class. It looks like this:
 
ServletContextListener  
 
After writing your web.xml, now create three classes in the com.example package. The three classes that we will be using are:
  1. MyServletContextListener.java
  2. MyDatabase.java
  3. MyTestServlet.java
1. The MyServletContextListener class implements the ServletContextListener interface to use the context parameters from the XML Deployment Descriptor and create the Connection Object. The interface contains the two methods contextIntialized() and contextDestroyed(). The contextInitialized() method takes a ServletContextEvent reference as an argument that creates the object for ServletContext. The object of ServletContext gets the parameters from the web.xml file.
 
Now an object of the MyDatabase class is created and these parameters are passed into it as arguments. This object is set as the context attribute so that it can be used by another servlet or JSP in the web application.
 
The source code for MyServletContextListener is:
  1. package com.example;  
  2. import javax.servlet.ServletContext;  
  3. import javax.servlet.ServletContextEvent;  
  4. import javax.servlet.ServletContextListener;  
  5. public class MyServletContextListener implements ServletContextListener{  
  6.       public void contextInitialized(ServletContextEvent event)  
  7.       {  
  8.             ServletContext context=event.getServletContext();  
  9.             String url=context.getInitParameter("URL");  
  10.             String database=context.getInitParameter("Database name");  
  11.             String username=context.getInitParameter("Username");  
  12.             String password=context.getInitParameter("password");  
  13.             MyDatabase mydb=new MyDatabase(url+database,username,password);  
  14.             context.setAttribute("Database", mydb);  
  15.       }  
  16.       public void contextDestroyed(ServletContextEvent event)  
  17.       {  
  18.       }  
  19. }  
2. My Second class, in other words the "MyDatabase" class, will use the parameters as the argument to the constructor and will connect to the database. This class has a getter method to get the object of the connection .The source code for this class is:
  1. package com.example;  
  2. import java.sql.Connection;  
  3. import java.sql.DriverManager;  
  4. import java.sql.SQLException;  
  5. public class MyDatabase {  
  6.       private  Connection con;  
  7.       public Connection getCon() {  
  8.             return con;  
  9.       }  
  10.       public MyDatabase(String url,String username,String password) {  
  11.             try {  
  12.                   Class.forName("oracle.jdbc.driver.OracleDriver");  
  13.                   this.con = DriverManager.getConnection(url,username,password);  
  14.             } catch (ClassNotFoundException e) {  
  15.                   // TODO Auto-generated catch block  
  16.                   e.printStackTrace();  
  17.             } catch (SQLException e) {  
  18.                   // TODO Auto-generated catch block  
  19.                   e.printStackTrace();  
  20.             }  
  21.       }  
  22. }  
3. My third class is a servlet to test whether the connection is made. First we create a Print Writer object so that we can print the statement in the browser. Now we get the context attribute that we have set in our first class, in other words the MyServletContextListener class to provide the object of the MyDatabase class. This object gets the connection object. This connection object now can be used to interact with the database. The code for that class is:

  1. package com.example;  
  2. import java.io.IOException;  
  3. import java.io.PrintWriter;  
  4. import java.sql.Connection;  
  5. import java.sql.SQLException;  
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.annotation.WebServlet;  
  8. import javax.servlet.http.HttpServlet;  
  9. import javax.servlet.http.HttpServletRequest;  
  10. import javax.servlet.http.HttpServletResponse;  
  11. /** 
  12.  * Servlet implementation class MyTestServlet 
  13.  */  
  14. @WebServlet("/MyTestServlet")  
  15. public class MyTestServlet extends HttpServlet {  
  16.     private static final long serialVersionUID = 1 L;  
  17.     /** 
  18.      * Default constructor. 
  19.      */  
  20.     public MyTestServlet() {  
  21.         // TODO Auto-generated constructor stub  
  22.     }  
  23.     /** 
  24.      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 
  25.      */  
  26.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  27.         // TODO Auto-generated method stub  
  28.         PrintWriter out = response.getWriter();  
  29.         MyDatabase mydata = (MyDatabase) getServletContext().getAttribute("Database");  
  30.         Connection con = mydata.getCon();  
  31.         if (con != null) {  
  32.             out.println("Database is connected");  
  33.         } else {  
  34.             out.println("Database is not connected");  
  35.         }  
  36.     }  
  37.     /** 
  38.      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 
  39.      */  
  40.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}  
  41. }  
Now run the servlet on the server. If the connection is made to the database then you will get the output "Database is connected" on the browser and if it is not connected then you will get "Database is not connected" as output.