In general, a lot of developers still using the 'manual' ways, demonstrated below, of opening connections to the database. Not only is opening and closing connections to the database expensive and will directly impact the performance and scalability of your application, you also run the risk of not closing your connections and releasing the resources which can cause some serious memory leaks.
Today I will go over configuring a DataSource on Tomcat and accessing this data source using JNDI.
Add Context in server.xml file of Tomcat Server Like
maxActive="20" maxIdle="10" maxWait="-1" name="jdbc:/sampledatasource"
username="test" password="test" type="javax.sql.DataSource"
url="jdbc:oracle:thin:@test:1521:test123" />
Where docBase is name of the project and we have given as TomJNDIEX.
In Resource tag we have to give driver class name, name(jndi), username, password and url.
U can also give maxActive,maxIdle,maxWait.
Add resource-ref in project web.xml file
Oracle Datasource example
jdbc:/iprudatasrc
javax.sql.DataSource
Container
Include classes12.jar or ojdbc14.jar file in tomcat lib folder
public Connection getDbConnection() {
Connection conn;
try {
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
DataSource ds = (DataSource) envContext.lookup(jdbc:/sampledatasource);
conn = ds.getConnection();
log.info("Connection Created...!");
} catch (javax.naming.NamingException ne) {
ne.printStackTrace();
} catch (java.sql.SQLException se) {
se.printStackTrace();
}
return conn;
}
The Following Example will explains the above concept
The IDE I have used for this application is is (Eclipse IDE)
JNDITestAction.java:
package com.vam.action;
import com.vam.DAO.TestForGettingData;
import com.opensymphony.xwork2.ActionSupport;
/**
* @author nagarajuv
*
*/
public class JNDITestAction extends ActionSupport{
private static final long serialVersionUID = 1L;
public String getAllEmployees(){
System.out.println("In JNDITestAction--->getAllEmployees()");
try{
TestForGettingData empl = new TestForGettingData();
empl.empList();
addActionMessage("Data Retrieved");
}catch(Exception e){
System.out.println("Exception--->"+e);
}
return "success";
}
}
BaseDAO.java:
Package com.vam.DAO;
import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* @author nagarajuv
*
*/
public class BaseDAO {
/** The conn. */
protected Connection conn = null;
/** The log. */
public static Log log = LogFactory.getLog(BaseDAO.class);
/**
* This method gets a database connection..
*
* @param jndiName String jndi name of the data source
*
* @return Connection
*
* @throws DAOException the DAO exception
*
* @exception DAOException
*/
public Connection getConnection(String jndiName) throws DAOException{
log.info("In getConnection()----->");
try{
Context initContext = new InitialContext();
Context envContext = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup(jndiName);
conn = ds.getConnection();
log.info("Connection Created...!");
}catch(javax.naming.NamingException ne) {
ne.printStackTrace();
throw new DAOException(ne.getMessage());
}catch(java.sql.SQLException se) {
se.printStackTrace();
throw new DAOException(se.getMessage());
}
return conn;
}
/**
* This method closes the existing DB connection..
*
* @return void
*
* @throws DAOException the DAO exception
*
* @exception DAOException
*/
public void closeConnection() throws DAOException
{
try
{
if(conn != null)
{
conn.close();
}
}
catch(java.sql.SQLException se)
{
throw new DAOException(se.getMessage());
}
}
}
BeanConstants.java:
package com.vam.DAO;
/**
* The Class BeanConstants.
*/
public final class BeanConstants {
/** The DATASOURC e_ jnd i_ name. */
public static String DATASOURCE_JNDI_NAME ="jdbc:/iprudatasrc";
}
DAOException.java:
package com.vam.DAO;
public class DAOException extends Exception {
/**
* Instantiates a new dAO exception.
*/
public DAOException(){
super();
}
/**
* Instantiates a new dAO exception.
*
* @param message the message
*/
public DAOException(String message){
super(message);
}
/**
* Instantiates a new dAO exception.
*
* @param throwable the throwable
*/
public DAOException(Throwable throwable){
super(throwable.getLocalizedMessage());
}
}
TestForGettingData.java:
package com.vam.DAO;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* @author nagarajuv
*
*/
public class TestForGettingData {
public void empList()throws Exception{
System.out.println("In TestForGettingData--->empList()");
BaseDAO baseDAO = new BaseDAO();
BeanConstants beanConstants = new BeanConstants();
Connection conn = baseDAO.getConnection(beanConstants.DATASOURCE_JNDI_NAME);
Statement s = conn.createStatement();
ResultSet rset = s.executeQuery("select empid,firstname from SAMPLE_EMP order by empid");
while(rset.next()){
System.out.println("empId is --->"+rset.getInt("EMPID")+"empName is --->"+rset.getString("FIRSTNAME"));
}
}
}
struts.xml:
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
/jsppages/Success.jsp
web.xml:
TomJNDIEX
struts2
org.apache.struts2.dispatcher.FilterDispatcher
struts2
/*
/jsppages/index.jsp
404
/pagenotfound.jsp
java.lang.Exception
/error.jsp
Oracle Datasource example
jdbc:/iprudatasrc
javax.sql.DataSource
Container
login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>Index Page</title>
</head>
<body>
<center>
<a href="getAllEmployees.action">JNDI Test</a>
</center>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!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>Success Page</title>
</head>
<body>
Success
<font color="#E3170D"><s:actionmessage/></font>
</body></html>
Enjoy with this code. All the best.
0 comments:
Post a Comment