[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

How to use classes (defined in a package) inside a jsp function?

Posted on 2005-04-25
10
Medium Priority
?
348 Views
Last Modified: 2008-03-04
I want to run SQL queries from inside a function that I've written in my jsp.But inside the function, the classes defined in the package java.sql.*(or any other package) don't get identified.I need to call the function several times from my main program. The classes Class,Connection,Statement,Resultset etc. get recognized in the main  program but when called from the function, it gives an error- class Class, Connection, Statement, Resultset etc. not found.

My code is as follows-
----------------------------------------------------------------------------------------------------
<html>
<%@ page import="java.io.*, java.sql.*"%>
<head><title>Try Page</title></head>
<body>
<%
            // ----- My main program ( : calls the function preorder several tmes)
            // P,T,V,leaf defined & initialized earlier

            n = preorder(P,T,V,leaf,0,0);
            
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection CN=null;
                          Statement ST=null;
                          ResultSet RS=null;
CN=DriverManager.getConnection"jdbc:odbc:chandanDSN","chandan_sql","chandan123");
                          ST=CN.createStatement();
                           RS=ST.executeQuery("--SQL Query--");
            while(RS.next())            {
                  // do some action
            }

// Here the query runs fine

%>
~~~~~~~~~~~~~~~ My function ~~~~~~~~~~~~~~~            
<%!      int preorder(int[] P,int[] Path,int[] V,int[] leaf,int i,int c)
      {

// But inside this function, I'm not being able to run the query.It gives "class not found" error, although the package java.sql.* is imported on top of the page and the classes used here are present in that package and don't give an error when used in the main-code.

            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection CN=null;
                          Statement ST=null;
                          ResultSet RS=null;
CN=DriverManager.getConnection"jdbc:odbc:chandanDSN","chandan_sql","chandan123");
                          ST=CN.createStatement();
                            RS=ST.executeQuery("--SQL Query--");
            while(RS.next())            {
                  // do some action
            }
            // Perform necessary calculations
            return 0;
      }                  
%>      
</body></html>
----------------------------------------------------------------------------------------------------

Is there any method by which I can call this function from the main code, make it do some database query and return the result back to the main code each time it is called?

0
Comment
Question by:ManiBhushan Kumar
  • 4
  • 2
  • 2
8 Comments
 
LVL 35

Expert Comment

by:TimYates
ID: 13858197
You still use the

<%@ page import="java.io.*, java.sql.*"%>

line yeah?
0
 
LVL 29

Expert Comment

by:bloodredsun
ID: 13858203
Try doing it this way, so that instead of having your code in each page, you re-use the code via a javabean.


ConnectionBean.java code // our javabean
<code>
package com.bloodredsun.beans ;
import java.sql.*;

public class Connectionbean{

private Connection conn ;
private Statement stmt ;
private static final String driver = "" ; // your db driver
private static final String dbURL= "" ; //your db url
private static final String login= "" ; // your db login
private static final String password= "" ; //your db password


  public ConnectionBean(){
    try{
      Class.forName( driver ) ;
      conn = DriverManager.getConnection(dbURL, login, password);
      stmt = conn.createStatement() ;

    }catch (Exception e){
      System.out.print("Whoops, buggered") ;
    }
  }//end ConnectionBbean constructor

      public ResultSet executeQuery ( String pSql){
      return stmt.executeQuery( pSql ) ;
      }
}//end ConnectionBean.java
</code>

Database.jsp code
<code>
<%@ page import="java.sql.*, com.bloodredsun.beans.*" %>
<jsp:useBean id="beanconnection" class="ConnectionBean" scope="request"/>
<html>
<body>
<%
String sql = "Select * from myTable" ;
ResultSet rs = beanconnection.executeQuery( sql) ;
%>
<%-- We now have the ResultSet, do what you will --%>
<%
while ( rs.next() ){
%>
A line of db stuff <%= rs.getString("id") %>

<%
}
%>
</body>
</html>
</code>

This is bare-arsed stuff, you will have to complete it with the normal extra methods in the bean for closing the connection, and other things like that and therer is minimal exception handling (in fact I've not tested this but written it straight out, but the theory is sound). What you can see is that Javabeans allow you to COMPONENTIZE code in that the code required for creating the db connection and statement were put in the JavaBean. This can then be dropped in as many pages as you like with out the need for repeatedly setting up the connection.

Once you have got used to JavaBeans in your JSP, I would recommend then doing it in a servlet. Then, once you've done that, have a look at custom tags and you'll see why JSTL is so popular (JSTL just being a set of standardised custom tags).

My next advice would be to look at dataSources and connection pools, this has a huge performance benefit for larger projects and also takes you into the world of JNDI (which isn't a frightening as it seems!).

Good luck and happy coding.
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13858210
>> It gives "class not found" error

Can you post the actual error?

And can you post the actual JSP that doesn't work, rather than just the function?

Tim
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 

Author Comment

by:ManiBhushan Kumar
ID: 13858442
// The Actual code is :

<html>
<%@ page import="java.io.*, java.sql.*"%>

<head><title>Try Page</title></head>
<body><br><br><br><br><br><br><br><br>
<%
      int n,i,x=1;
      int P[]=new int[5];      int T[]=new int[5];      int V[]=new int[5];      int leaf[]=new int[5];      int Path[]=new int[10];

      V[0]=3;      V[1]=4;      V[2]=5;      V[3]=8;      V[4]=6;      P[0]=0;      P[1]=0;      P[2]=0;      P[3]=1;      P[4]=1;      T[0]=0;      T[1]=0;      T[2]=0;      T[3]=0;      T[4]=0;
      leaf[0]=0;      leaf[1]=0;      leaf[2]=1;      leaf[3]=1;      leaf[4]=1;
      
      n=preorder(P,T,V,leaf,0,0);
      //n=preorder1(P,Path,V,leaf,0,0);
      //out.println("n="+n);

      for(i=0;i<n;i++)
                  out.println("_______T["+i+"]: "+T[i]);
      
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection CN=null;
        Statement ST=null;
        ResultSet RS=null;
            CN=DriverManager.getConnection("jdbc:odbc:chandanDSN","chandan_sql","chandan123");
        ST=CN.createStatement();
       
      RS=ST.executeQuery("select Pname from Places");
      while(RS.next())      {}
%>
            
<%!      int preorder(int[] P,int[] Path,int[] V,int[] leaf,int i,int c)
      {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            int z;
            Path[c++]=V[i];
            if(leaf[i]==1) return c;
            
            for(z=i+1;z<5;z++)
                  if(P[z]==i)
                  {
                        c = preorder1(P,Path,V,leaf,z,c);
                        Path[c++]=V[i];                        
                  }      
            return c;
      }                  
%>      
</body></html>
0
 
LVL 35

Expert Comment

by:TimYates
ID: 13858453
try defining the function before the rest of your JSP code...

<html>
<%@ page import="java.io.*, java.sql.*"%>
<%!    
     public int preorder(int[] P,int[] Path,int[] V,int[] leaf,int i,int c)
     {
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

          int z;
          Path[c++]=V[i];
          if(leaf[i]==1) return c;
         
          for(z=i+1;z<5;z++)
               if(P[z]==i)
               {
                    c = preorder1(P,Path,V,leaf,z,c);
                    Path[c++]=V[i];                    
               }    
          return c;
     }              
%>    

<head><title>Try Page</title></head>
<body><br><br><br><br><br><br><br><br>
<%
     int n,i,x=1;
     int P[]=new int[5];     int T[]=new int[5];     int V[]=new int[5];     int leaf[]=new int[5];     int Path[]=new int[10];

     V[0]=3;     V[1]=4;     V[2]=5;     V[3]=8;     V[4]=6;     P[0]=0;     P[1]=0;     P[2]=0;     P[3]=1;     P[4]=1;     T[0]=0;     T[1]=0;     T[2]=0;     T[3]=0;     T[4]=0;
     leaf[0]=0;     leaf[1]=0;     leaf[2]=1;     leaf[3]=1;     leaf[4]=1;
     
     n=preorder(P,T,V,leaf,0,0);
     //n=preorder1(P,Path,V,leaf,0,0);
     //out.println("n="+n);

     for(i=0;i<n;i++)
               out.println("_______T["+i+"]: "+T[i]);
     
          Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
          Connection CN=null;
        Statement ST=null;
        ResultSet RS=null;
          CN=DriverManager.getConnection("jdbc:odbc:chandanDSN","chandan_sql","chandan123");
        ST=CN.createStatement();
       
     RS=ST.executeQuery("select Pname from Places");
     while(RS.next())     {}
%>
</body></html>
0
 

Author Comment

by:ManiBhushan Kumar
ID: 13907820

No it doesn't work.

My problem is-----------

I am not being able to run any SQL Query inside a JSP function.The Driver doesn not get loaded from inside the function.A simple code is :

<%@ page import="java.io.*, java.sql.*"%>
<%
      int n= func();
      out.println(" n="+n);
%>

<%! public int func()
      {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            /*Connection CN=null;
        Statement ST=null;
        ResultSet RS=null;
            CN=DriverManager.getConnection("jdbc:odbc:chandanDSN","chandan_sql","chandan123");
        ST=CN.createStatement();
       
            RS=ST.executeQuery("select Pname from Places");
            while(RS.next())      {}*/
            

            return 5;      
      }
%>

--------------------------------------------------------
The error I'm getting is :
Generated servlet error:
C:\Apache\Tomcat 5\work\Catalina\localhost\chandan\org\apache\jsp\test_jsp.java:14: unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
 ********************************************************************

Can someone help please...
0
 
LVL 35

Accepted Solution

by:
TimYates earned 400 total points
ID: 13908129
That's because you have to catch the classNotFound exception

or you can throw it...

change

<%! public int func()

to

<%! public int func() throws Exception
0
 
LVL 29

Expert Comment

by:bloodredsun
ID: 15344550
Agreed
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This shares a stored procedure to retrieve permissions for a given user on the current database or across all databases on a server.
MSSQL DB-maintenance also needs implementation of multiple activities. However, unprecedented errors can hamper the database management. In that case, deploying Stellar SQL Database Toolkit ensures fast and accurate database and backup repair as wel…
This video shows how to quickly and easily deploy an email signature for all users in Office 365 and prevent it from being added to replies and forwards. (the resulting signature is applied on the server level in Exchange Online) The email signat…
This lesson discusses how to use a Mainform + Subforms in Microsoft Access to find and enter data for payments on orders. The sample data comes from a custom shop that builds and sells movable storage structures that are delivered to your property. …
Suggested Courses
Course of the Month18 days, 20 hours left to enroll

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question