This article explains connecting to a database using ServletContextListener. We should however first know why we need 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".
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.
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:
After writing your web.xml, now create three classes in the com.example package. The three classes that we will be using are:
- MyServletContextListener.java
- MyDatabase.java
- 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:
package com.example;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyServletContextListener implements ServletContextListener{
public void contextInitialized(ServletContextEvent event)
{
ServletContext context=event.getServletContext();
String url=context.getInitParameter("URL");
String database=context.getInitParameter("Database name");
String username=context.getInitParameter("Username");
String password=context.getInitParameter("password");
MyDatabase mydb=new MyDatabase(url+database,username,password);
context.setAttribute("Database", mydb);
}
public void contextDestroyed(ServletContextEvent event)
{
}
}
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:
package com.example;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MyDatabase {
private Connection con;
public Connection getCon() {
return con;
}
public MyDatabase(String url,String username,String password) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
this.con = DriverManager.getConnection(url,username,password);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
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:
package com.example;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class MyTestServlet
*/
@WebServlet("/MyTestServlet")
public class MyTestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public MyTestServlet() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=response.getWriter();
MyDatabase mydata=(MyDatabase)getServletContext().getAttribute("Database");
Connection con=mydata.getCon();
if(con!=null)
{
out.println("Database is connected");
}
else
{
out.println("Database is not connected");
} }
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
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.