I hope I am not asking a duplicate question just because I was unable to find an answer. I am getting this error:
javax.naming.NamingException: Lookup failed for 'jdbc/osclassDB' in SerialContext
This is what I did: I set up a JDBC Connection Pool and a JDBC Resource pointing to that pool (both in Glassfish).
Then I told my web.xml that there is a JDBC Resource:
<resource-ref>
<res-ref-name>jdbc/osclassDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
And then I tried using that resource in a Servlet:
Connection connection = null;
try {
InitialContext initialContext = new InitialContext();
//Context dbContext = (Context) initialContext.lookup("java:comp/env");
DataSource dataSource = (DataSource) initialContext.lookup("jdbc/osclassDB");
connection = dataSource.getConnection();
if (connection == null) {
throw new SQLException("Error establishing connection!");
}
// some queries here
}
// catch and finally close connection
But when I call the Servlet
it throws me the NamingException
and tells me that the Lookup failed for 'jdbc/osclassDB' in SerialContext
What am I doing wrong here? is it the web.xml? did I miss something? Thank you for your help!
Solved the problem:
1st by adding a sun-web.xml that links the resource reference from the web.xml to an actual jndi-name (the one I setup on Glassfish). Normally, that shouldn't be necessary (says Oracle) but I did it anyways [Edit: as it turns out, it is really not necessary! ]
2nd I left out the "jdbc". In the servlet, the web.xml and the sun-web.xml it is now just called "osclassDB" (my resource name) instead of "jdbc/osclassDB"
now it looks like this:
web.xml
<resource-ref>
<res-ref-name>osclassDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
sun-web.xml
<resource-ref>
<res-ref-name>osclassDB</res-ref-name>
<jndi-name>osclassDB</jndi-name>
</resource-ref>
in the servlet
Context dbContext = (Context) initialContext.lookup("java:comp/env");
DataSource dataSource = (DataSource) dbContext.lookup("osclassDB");
connection = dataSource.getConnection();
[Edit:] the sun-web.xml is really not necessary