Use JNDI to get database connection or data source : JNDI « Servlets « Java






Use JNDI to get database connection or data source

 
 
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

public class Main extends HttpServlet implements Servlet {

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

    DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

    response.setContentType("text/html");
    PrintWriter writer = response.getWriter();

    Connection connection = getConnection();
    if (connection != null) {
      String sql = "SELECT SYSDATE FROM DUAL";
      try{
      PreparedStatement statement = connection.prepareStatement(sql);
      ResultSet rs = statement.executeQuery();

      while (rs.next()) {
        Date date = rs.getDate("SYSDATE");
        writer.println("The current date is " + dateFormat.format(date));
      }
      connection.close();
      }catch(Exception e){
        System.out.println(e);
      }
    }
  }

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

  private Connection getConnection() {
    Connection connection = null;
    try {
      InitialContext context = new InitialContext();
      DataSource dataSource = (DataSource) context.lookup("jdbc/DataSource");
      connection = dataSource.getConnection();
    } catch (NamingException e) {
      e.printStackTrace();
    } catch (SQLException e) {
      e.printStackTrace();
    }
    return connection;
  }
}

   
  








Related examples in the same category

1.Servlet JNDI and Bean
2.JNDI Filter
3.Email JNDI Filter
4.Web JNDI