Using Datasource In Application


Once we bind the datasource with the tomcat then we need to use it in the application. This can be done by defining the resource in the web.xml file and then writing the Java code to call the datasource in the application.


1. Writing the code in the web.xml file of the web application:-


<resource-ref>

    <description>DB Connection</description>

    <res-ref-name>jdbc/TestDB</res-ref-name>

    <res-type>javax.sql.DataSource</res-type>

    <res-auth>Container</res-auth>

</resource-ref>


2. Writing the Java code to call the datasource.The below is test.jsp for the same.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@page import="javax.naming.*,java.sql.*,javax.sql.*;" %>


<!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>

<%

    Context initContext = new InitialContext();

    Context envContext = (Context)initContext.lookup("java:/comp/env");

    DataSource ds = (DataSource)envContext.lookup("jdbc/TestDB");

    Connection con = null;

    Statement stmt = null;

    try{

        con = ds.getConnection();

       out.println("Conection Established");

    }catch(Exception e){

        e.printStackTrace();

        out.println("Exception Occured");

    }finally{

        if(con != null) con.close();

    }

%>


</body>

</html>

                    

Copyright © 2012 VisualBuilder. All rights reserved