servletcontextlistener example for database connection


servletcontextlistener example for database connection

servletcontextlistener example for database connection will help you in real time project, servletcontextlistener example for database connection is an standard approach by which we can use JDBC API  for record insertion or updattion etc.

Example

  1. Create table with student name in oracle database.
  2. Create JdbcDataSourceManager class to initialize Datasource.
  3. Create web.xml and pass database configuration inside context-param.
  4. Create DataSourceConnector by implementing ServletContextListener and override contextInitialized() and contextDestroyed() method.
  5. Create SaveData Servlet to save data in oracle database.
  6. Create Jsp page to pass information to servlet.

Create student table in oracle

SQL> create table student(name varchar2(20), email varchar2(20), address varchar2(20));

Create JdbcDataSourceManager class

package com.javagf.utils;

import java.sql.SQLException;

import javax.sql.DataSource;

import oracle.jdbc.pool.OracleDataSource;

public class JdbcDataSourceManager {

 public static DataSource getOracleDS(String url, String user, String pass) {

   OracleDataSource oracleDS = null;
   try {
     oracleDS = new OracleDataSource();
     oracleDS.setURL(url);
     oracleDS.setUser(user);
     oracleDS.setPassword(pass);
    } catch (SQLException e) {
     e.printStackTrace();
   }
     return oracleDS;
  }

   public void closeConnection() {
    // close connection
   }
}

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"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 id="WebApp_ID" version="3.0">
 <display-name>ListenerExample</display-name>
 <welcome-file-list>
 <welcome-file>register.jsp</welcome-file>
 </welcome-file-list>
 <context-param>
 <param-name>ORACLE_DB_URL</param-name>
 <param-value>jdbc:oracle:thin:@localhost:1521:xe</param-value>
 </context-param>
 <context-param>
 <param-name>ORACLE_DB_USERNAME</param-name>
 <param-value>system</param-value>
 </context-param>
 <context-param>
 <param-name>ORACLE_DB_PASSWORD</param-name>
 <param-value>manager</param-value>
 </context-param>
</web-app>

DataSourceConnector Listener class

package com.javagf.example;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.sql.DataSource;

import com.javagf.utils.JdbcDataSourceManager;

/**
 * DataSourceConnector class is use to initialize JDBC Datasource in java
 *
 */
@WebListener
public class DataSourceConnector implements ServletContextListener {

 /*
 * contextDestroyed() method will be called before application deployment
 * itself
 */
 public void contextInitialized(ServletContextEvent servletContextEvent) {
 ServletContext ctx = servletContextEvent.getServletContext();

   String url = ctx.getInitParameter("ORACLE_DB_URL");
   String user = ctx.getInitParameter("ORACLE_DB_USERNAME");
   String pass = ctx.getInitParameter("ORACLE_DB_PASSWORD");
   DataSource dataSource = JdbcDataSourceManager.getOracleDS(url, user, pass);
   ctx.setAttribute("Datastore", dataSource);
   System.out.println("Database connection initialized.");

 }

 /*
 * contextDestroyed() method will be called after application shutdown
 * 
 */
 public void contextDestroyed(ServletContextEvent servletContextEvent) {
   ServletContext ctx = servletContextEvent.getServletContext();
   JdbcDataSourceManager jdbcDataSourceManager = (JdbcDataSourceManager) ctx.getAttribute("Datastore");
   jdbcDataSourceManager.closeConnection();
   System.out.println("Database connection closed.");
 }

}

SaveData Servlet

package com.javagf.example;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
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;
import javax.sql.DataSource;

@WebServlet("/SaveData")
public class SaveData extends HttpServlet {
 private static final long serialVersionUID = 1L;

 @Override
 protected void service(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 PrintWriter out = response.getWriter();
 String name = request.getParameter("name");
 String email = request.getParameter("email");
 String address = request.getParameter("address");
 DataSource dataSource = (DataSource) request.getServletContext().getAttribute("Datastore");
 String query = "insert into student values(101,'vikash','Hyderabad')";
 Connection con = null;
 try {
 con = dataSource.getConnection();
 PreparedStatement preparedStatement = null;

 String insertTableSQL = "INSERT INTO student" + "(name, email, address) VALUES" + "(?,?,?)";

 preparedStatement = con.prepareStatement(insertTableSQL);

 preparedStatement.setString(1, name);
 preparedStatement.setString(2, email);
 preparedStatement.setString(3, address);

 preparedStatement.executeUpdate();
 con.close();
 out.println("Data Saved.");
 } catch (SQLException e) {
 e.printStackTrace();
 }
 }

 protected void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 service(request, response);
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
 service(request, response);
 }

}

register.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>
 <form action="${pageContext.request.contextPath}/SaveData"
 method="post">
 <table>
 <tr>
 <td>Name</td>
 <td><input type="text" name="name"></td>
 </tr>
 <tr>
 <td>Email</td>
 <td><input type="text" name="email"></td>
 </tr>
 <tr>
 <td>Address</td>
 <td><input type="text" name="address"></td>
 </tr>
 <tr>
 <td colspan="2"><input type="submit" value="Submit"></td>

 </tr>
 </table>
 </form>
</body>
</html>

Output

Data saved.






Full-stack web and mobile app development company Contact Us : Skype: indore.webcoder Email: info@w3sparks.com Sales: +91 8085506229