When I write code in <%, I can use javax.naming, but when I write code in <%!, I get an error that javax.naming does not exist.
some examples:
<% Javax.naming.InitialContext ic = new Javax.naming.InitialContext(); %> fine
<%! void foo() { Javax.naming.InitialContext ic2 = new Javax.naming.InitialContext(); } %> error
The exact error:
rptCountsRecon_jsp.java:22: package Javax.naming does not exist
Javax.naming.Context init = new Javax.naming.InitialContext();
I am sortof new to Java and am very new to JSP.
EDIT: added the foo method to the second example, because it may help understand my issue. Also added the exact error from Tomcat.
EDIT 2: tried adding the prefix to Context, and got a similar error.
EDIT 3: Side question… The current code gives the following error:
try
{
javax.naming.Context init = new javax.naming.InitialContext();
Context ctx = (Context) init.lookup("java:comp/env");
String jndiName = getServletContext().getInitParameter("jndiName");
DataSource ds = (DataSource) ctx.lookup(jndiName);
Connection dbConn = ds.getConnection();
PreparedStatement pstmnt = dbConn.prepareStatement(sql);
for(int i=0; i!=binds.size(); ++i)
pstmnt.setString(i+1, binds.elementAt(i)); //binds index starts at 1 -_-
return pstmnt.executeQuery();
} catch (Exception e) {
//out.println("A naming exception occured... I don't know how to get the info of it.");
return null;
}
rptCountsRecon_jsp.java:28: unreported exception java.sql.SQLException; must be caught or declared to be thrown
Connection dbConn = ds.getConnection();
First of all this type code should be in a servlet, not in a JSP.
Declaration (
<%!):ic2is a member variable. And the reason that you can’t doic2 = new javax.naming.InitialContext();there is because the constructor throwsjavax.naming.NamingException.Imagine something as follows:
Scriptlet (
<%):And the reason that it can be done there (within scriplet) is because everything in the scriplet goes inside a
tryblock of the generated JSP service method.Imagine something as follows:
I think it will make more sense if you read more about JSP lifecycle.