Java Servlet Programing Laungage

Java Servlet Projects

Servlet Project 3

adplus-dvertising
Create an application for access JNDI connectionPool into Servlet
Previous Home Next

This Servlet application, accesses Java Naming and Directory Interface (JNDI) connection in Servlet by using Tomcat web server and connect to r4r table in database.

Application directory structure

context.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Setting Up a Connection Pool on the Tomcat Web Server
	and connect to the r4r table in database,
   more database connection pooling functionality,
   see: http://commons.apache.org/dbcp/
-->
<Context antiJARLocking="true" path="/JNDI" 
              reloadable="true" crossContext="true">
    <Resource name="jdbc/r4r" auth="Container"
        type="javax.sql.DataSource"
          maxActive="20" maxIdle="10" maxWait="500"
 username="root" password="root" driverClassName="com.mysql.jdbc.Driver"
              url="jdbc:mysql://localhost:3306/r4r"/>
</Context>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
     <servlet-name>JndiServlet</servlet-name>
     <servlet-class>r4r.Servlet.JndiServlet</servlet-class>
</servlet>
<servlet-mapping>
     <servlet-name>JndiServlet</servlet-name>
     <url-pattern>/JndiServlet</url-pattern>
</servlet-mapping>
<session-config>
        <session-timeout>
            30
        </session-timeout>
</session-config>
<!-- <resource-ref> provide information needed by the server -->
<resource-ref>
    <description>used to extract data from r4r database</description>
	<res-ref-name>jdbc/r4r</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
    <res-sharing-scope>Shareable</res-sharing-scope>
    </resource-ref>
</web-app>

Index.jsp

<%-- 
 Document: index.jsp
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>r4r.co.in-index</title>
 </head>
 <body>
  <h1>JNDI-Servlet Example!</h1>
  <a href="JndiServlet">JndiServlet</a><br/>
  <a href="TestJsp.jsp">Test Page</a>
 </body>
</html>

TestJsp.jsp

<%-- 
 Document: TestJsp.jsp
--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<sql:query var="result" dataSource="jdbc/r4r">
 SELECT * FROM R4R.CUSTOMER
</sql:query>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
 <head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>r4r.co.in-Test</title>
 </head>
 <body>
  <h1>JNDI- Servlet!Fetch data from R4R.CUSTOMER Table</h1>
  <table border="1">
   <!-- r4r.customer column headers name -->
<tr>
   <c:forEach var="columnName" items="${result.columnNames}">
   <th><c:out value="${columnName}"/></th>
   </c:forEach>
</tr>
<!-- r4r.customer column data -->
<c:forEach var="row" items="${result.rowsByIndex}">
 <tr>
  <c:forEach var="column" items="${row}">
<td><c:out value="${column}"/></td>
  </c:forEach>
 </tr>
</c:forEach>
  </table>
  <a href="index.jsp">Return to Index Page</a>
 </body>
</html>

Servlet Program

/*
 * Save as a JndiServlet.java
 */
package r4r.Servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 *
 * @author R4R
 */
public class JndiServlet extends HttpServlet {
 protected void processRequest(HttpServletRequest request,
  HttpServletResponse response)
    throws ServletException, IOException {
  response.setContentType("text/html;charset=UTF-8");
  PrintWriter out = response.getWriter();
  try
  {
	
  }
  catch ()
  {
  }
  {
	out.println("<html>");
    out.println("<head>");
    out.println("<title>" + getServletInfo() + "</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("<h1>Fetch data from JNDI PoolConnection</h1>");

// Obtain our environment naming context
javax.naming.Context initCtx = new javax.naming.InitialContext();
javax.naming.Context envCtx = (javax.naming.Context) 
	          initCtx.lookup("java:comp/env");
// Allocate and use a connection from the pool
javax.sql.DataSource ds = (javax.sql.DataSource)
	          envCtx.lookup("jdbc/r4r");
// Open SQL connection and fetch data from Pool table
java.sql.Connection conn = ds.getConnection();
java.sql.Statement s = conn.createStatement();
// execute SQL query
s.executeQuery("SELECT * FROM R4R.CUSTOMER");
java.sql.ResultSet rs = s.getResultSet();
while (rs.next()) {
 out.println("<b>" + rs.getString(2) + "</b><br/>");
}
out.println("</body>");
out.println("</html>");
conn.close(); // close SQL Connection
out.println("<a href=\"index.jsp\">Return to Index Page</a>");
  } catch (Exception ex) {
Logger.getLogger(JndiServlet.class.getName()).log
	              (Level.SEVERE, null, ex);
  } finally {
out.flush(); //free resource
out.close();
  }
 }

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

 @Override
 protected void doPost(HttpServletRequest request,
	HttpServletResponse response)throws ServletException,IOException
	 {
 // processRequest(request, response);
 }

 @Override
 public String getServletInfo() {
  return "r4r.co.in-JndiServlet";
 }
}
Output of Program
Previous Home Next