Can't access object using Java JNDI context lookup
I'm running Tomcat6 and want to access the datasource from my Servlet. But I'm getting
javax.naming.OperationNotSupportedException: can''t generate an absolute name for this namespace
at org.apache.naming.NamingContext.getNameInNamespace(NamingContext.java
:772)
My context.xml is under HomeController/META-INF/context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Context path="/HomeController">
<Resource name="jdbc/HomeController" auth="Container" type="javax.sql.DataSource" driverClass="com.microsoft.sqlserver.jdbc.SQLServerDriver"
acquireIncrement="5"
username="client"
password="1234"
jdbcUrl="jdbc:sqlserver://192.168.1.5:1433;databaseName=myDB;autoReconnect=true" />
</Context>
I also have the same context.xml renamed to my webapp "HomeController" and placed under TOMCAT_HOME/conf/Catalina/localhost/HomeController.xml.
My web.xml looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Home Controller</display-name>
<servlet>
<servlet-name>HomeController</servlet-name>
<servlet-class>com.home.controller.HomeController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HomeController</servlet-name>
<url-pattern>/HomeController</url-pattern>
</servlet-mapping>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/HomeController</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
In my Servlet I have this:
Connection conn = null;
Context ctx = null;
java.sql.Statement stmt = null;
try {
ctx = new InitialContext();
Context envCtx = (Context) ctx.lookup("java:comp/env"); //<--FAILS HERE
DataSource ds = (DataSo开发者_高级运维urce) envCtx.lookup("jdbc/EmscribeWS");
conn = ds.getConnection();
DatabaseMetaData mt = conn.getMetaData();
stmt = conn.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
I installed a fresh copy of Tomcat6 and placed the sqljdbc4.jar under TOMCAT_HOME/lib. I have no JARS under my HomeController/WEB-INF/lib.
It fails when executing "(Context) ctx.lookup("java:comp/env"); " in my Servlet.
Anyone knows why it fails when retrieving object?
Try it like this.
DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/HomeController");
You are attempting to lookup a resource reference, but have not specified the actual reference, which is why an absolute name cannot be generated.
精彩评论