Won Contests Let Us Talk Mail Me Light of Knowledge


O racle with Java using J2EE Architecture
  
 This Article with Code shows how to Connect to Oracle 9i Database using J2EE Deploytool

     This had always been the most Complicated Subject to Handle Because of Improper and Bad Documentations available over the net and Books u read , Thats one of the Reasons i delayed in writing in This Article and Most of the books never seem to answer your question.

     Oracle J2EE Setup is something which requires TEAM WORK and u should have very good relation with ur DBA , The man who setup your Oracle Server
=>> <<=

 
 Software's that you Need

1. J2EE1.3.1 - j2sdkee-1_3_1-win.exe
2. J2SDK1.3.1 - j2sdk-1_3_1_09-windows-i586.exe
3. Oracle 9i Client Setup
4. Macromedia HomeSite Editor[Optional]

 Initial Environmental Configuration

Assumption 1 : Your Java SDK is installed in C:\jdk1.3.1
Assumption 2 : Your Java J2EE is installed in C:\j2sdkee1.3.1
Assumption 3 : Your Java Oracle Client is set in D:\oracle

Right Click on My Computer Go to Properties and Environmental Variables and add System Variables

1. Variable Name : JAVA_HOME :: value C:\jdk1.3.1
2. Variable Name : J2EE_HOME :: value C:\j2sdkee1.3.1
3. Variable Name : path :: value [otherpaths];d:\oracle\ora81\bin;C:\jdk1.3.1\bin;C:\j2sdkee1.3.1\bin
4. Variable Name : CLASSPATH :: value C:\j2sdkee1.3.1\lib\j2ee.jar;C:\j2sdkee1.3.1\lib\ejb10deployment.jar;C:\j2sdkee1.3.1\lib\j2ee.jar; C:\j2sdkee1.3.1\lib\j2ee-ri-svc.jar;C:\j2sdkee1.3.1\lib\j2eetools.jar; C:\j2sdkee1.3.1\lib\jhall.jar;D:\oracle\ora81\jdbc\lib\classes12.zip
5. Edit userconfig.bat in C:\j2sdkee1.3.1\bin Directory and add this line at Bottom
SET J2EE_CLASSPATH=D:\oracle\ora81\jdbc\lib\classes12.zip;
Re-Start Your System after u make change

 TNSNAMES : D:\oracle\ora81\network\ADMIN\tnsnames.ora
This is one of the most important files your Entry must look something like this But PLEASE CONSULT YOUR ORACLE DBA while making changes in this file

EntryName =
(DESCRIPTION =
	(ADDRESS_LIST =
		(ADDRESS = (PROTOCOL = TCP)(HOST = oracle_host_server_name)(PORT = 1521))
	)
	(CONNECT_DATA = 
		(SERVICE_NAME = service_name)
	)
)
 Starting J2EE Server and Deploytool
 C:\>j2ee -verbose     This will start the J2EE Server
 C:\>j2ee -stop            This will stop the J2EE Server
 C:\>deploytool           This will start the Java GUI Deploytool
 The Simple JSP Code

We will write a small jsp code which looks into table "students" and gets the field "studentname" where the studentgrade matches some criteria from the initial parameters as defined in web.xml file .

Therefore this table students will have basically 3 fields , 1 studentid - Primary Key, 2 studentname, 3 studentgrade

Our Next step will be to write a JSP Code, which will

      1. Import Necessary Java Classes
      2. Get the Initial Parameters from web.xml file
      3. Build a small Database Query or Select statement based on this
      4. Connect to Oracle Database using Data Source lookup of JNDI *
      5. Display records in the result set and close connection
      * JNDI - Java Naming and Directory Interface
<HTML>           	
<HEAD>  
    <TITLE>
     James Smith's Java : james_smith73@yahoo.com
    </TITLE>
  </HEAD>
 <BODY bgcolor="#C0C0C0">
 <%@ page import="java.sql.*" %>
 <%@ page import="java.lang.*" %>
 <%@ page import="java.util.*" %>
 <%@ page import="javax.sql.*" %>
 <%@ page import="javax.naming.*" %>
 <%!
 //Get Initial Parameters from web.xml file
 ServletConfig cfg =null;
 String studentid=null;	
 public void jspInit()
 {
   cfg=getServletConfig();
   studentgrade = cfg.getInitParameter("studentgrade") ;
 }
 %>
 <%
 //Select Query 
 String query = "select studentname from students WHERE studentgrade='"+studentgrade+"'";
 Statement stmt = null;  
 Connection mycon = null; 
 //Connect to DB using JNDI lookup
 try
 {
    InitialContext ic = new InitialContext(); 
    mycon =  (( DataSource )ic.lookup("jdbc/Data")).getConnection(); 
 }
 catch(Exception e )
 { 
   e.printStackTrace();
 } 
 stmt = mycon.createStatement();
 ResultSet rs = stmt.executeQuery(query);
 String str1="";
 int foundrec = 0;
 while(rs.next())
 { 
   str1 = rs.getString(1);
   %>Student Name is : <%=str1%> <br> <%
 }
 rs.close();
 stmt.close();
 mycon.close();
 %<
 </body>
 </HTML>
Save the Above File in C:\Ear3 Directory
 C:\>j2ee -verbose  C:\>deploytool
 Verify Server Configuration / JNDI Name and Driver Class

     First we need to setup our Oracle Driver Class and JNDI Name and JDBC URL for this to happen Click on Tool -> Server Configuration in your Deploytool

     Click on Add Button Next to JDBC Drivers type oracle.jdbc.driver.OracleDriver Similarly click add button next to DataSource and Add JNDI name as jdbc/Data and the corresponding JDBC URL as jdbc:oracle:thin:@dbservername:1521:sid Observe the lines highligted and Talk to Your DBA about the JDBC URL part


 Clear Picture , Deploying J2EE Application Whats not there in the SUN SITE !

Select File -> New -> Application so that u can create a new Application




Create a Directory Example EAR3 under C:\ where your EAR file will be placed and this is NEW APPLICATION , ofcourse it can be any directory of ur choice




Deploytool Automatically Creates General , JNDI, Web Context and Security tabs




Since we are building a Web Application Select File -> New -> WebApplication




This will Launch New WebComponent Wizard




Select Create a New WAR File




Edit Button and Add our JSP File




Click OK, Next Select New Web Componet click on Radio Button JSP




Select the JSP File Name and Type in Web Component Display Name




Type in the Alias Name which is a part of Internet Address to Access the Web Page Say Next Till End




Click on Tools and Deploy Click Next




Enter Web Context Root Name which is the Part of our Web URL




You can See Deployment Progress Bar in Action Connecting the Server




Deployment Completed with No Errors




Click on the WebApp1 Application and in the Resource Reference Tab Type in the JNDI Name and Database Username and Password




Verify the JNDI Name in JNDI Tab This should match our DATASOURCE name in our JSP CODE
try
 {
    InitialContext ic = new InitialContext(); 
    mycon =  (( DataSource )ic.lookup("jdbc/Data")).getConnection(); 
 }
 catch(Exception e )
 { 
   e.printStackTrace();
 }

 Setting Up " studentgrade " as Init Parameters in web.xml file
In your web.xml now located in C:\j2sdkee1.3.1\public_html\myRoot3\WEB-INF Directory open it with word pad u can see Entry Like this , Add the lines Higlighted
<web-app>
  <display-name>WebApp1</display-name>
  <servlet>
    <servlet-name>JavaOracle</servlet-name>
    <display-name>JavaOracle</display-name>
    <jsp-file>/JavaOracle.jsp</jsp-file>	
  <init-param>
     <param-name>studentgrade</param-name> 
     <param-value>GradeA</param-value> 
   </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>JavaOracle</servlet-name>
    <url-pattern>/myAlias3</url-pattern>
  </servlet-mapping>
  <session-config>
    <session-timeout>30</session-timeout>
  </session-config>
</web-app>
This should match our lines in JSP code which calls initial Parameter
 ServletConfig cfg =null;
 String studentid=null;	
 public void jspInit()
 {
   cfg=getServletConfig();
   studentgrade = cfg.getInitParameter("studentgrade") ;
 }
 Check If J2EE Server is ON

In your Internet Explorer Type in http://localhost:8000/ u must see


 Launch Your Application

In your Internet Explorer Type in http://localhost:8000/< Context Name >/< Alias Name> u must see Values Pulled From Database


 Trouble Shooting

Error 1 : ORA-00600: internal error code, arguments: [ttcgcshnd-1]
Solution checkout the version of classes12.zip and download the latest from Oracle Site Don't go to OTN Error check u can be mislead by the Error Number Explanation     

Error 2 : Invalid URL Error
Solution check the URL it must be jdbc:oracle:thin:@OracleServerName:1521:SID Consult your DBA for OracleServerName , Port, and SID

Error 3 : Invalid Unername/ Password or Username / Password cannot be Null / Permission Denied
Solution checkout the Username Password Provided Resource Reference Settings Tab (see figure above)

Error 4 : Driver not Found
Solution See ur J2EE_CLASSPATH settings in userconfig.bat in C:\j2sdkee1.3.1\bin Directory and Classpath in Environmental Variables

 My Dream to be your Friend and Create a Group of Intelligent and Understanding Programmers
     If you like this article and/or code mailme or Join our small Java User Group which is by the Programmers for the Programmers ,
Till we meet next time BYE      Kind Regards - James Smith

  Java, J2EE, J2SE and all Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc.
in the United States and other countries.