【问题标题】:Can't access object using Java JNDI context lookup无法使用 Java JNDI 上下文查找访问对象
【发布时间】:2010-12-08 18:55:02
【问题描述】:

我正在运行 Tomcat6 并想从我的 Servlet 访问数据源。但我得到了

    javax.naming.OperationNotSupportedException: can''t generate an absolute name for this namespace
at org.apache.naming.NamingContext.getNameInNamespace(NamingContext.java
:772)

我的 context.xml 在 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>

我也有相同的 context.xml 重命名为我的 web 应用程序“HomeController”并放在 TOMCAT_HOME/conf/Catalina/localhost/HomeController.xml 下。

我的 web.xml 看起来像这样:

<?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>

在我的 Servlet 中有这个:

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 = (DataSource) envCtx.lookup("jdbc/EmscribeWS");

             conn = ds.getConnection();
             DatabaseMetaData mt = conn.getMetaData();                                                 
             stmt = conn.createStatement();                 

     } catch (Exception e) {
      e.printStackTrace();         
     }

我安装了 Tomcat6 的新副本并将 sqljdbc4.jar 放在 TOMCAT_HOME/lib 下。 我的 HomeController/WEB-INF/lib 下没有 JARS。

在我的 Servlet 中执行 "(Context) ctx.lookup("java:comp/env"); "时失败。

有人知道为什么在检索对象时会失败吗?

【问题讨论】:

    标签: java tomcat datasource tomcat6 jndi


    【解决方案1】:

    这样试试吧。

    DataSource ds = (DataSource) ctx.lookup("java:comp/env/jdbc/HomeController");
    

    您正在尝试查找资源引用,但尚未指定实际引用,这就是无法生成绝对名称的原因。

    【讨论】:

    • Tomcat 启动时出现其他错误。在我修复这些之后,一切正常。
    猜你喜欢
    • 1970-01-01
    • 2012-05-06
    • 1970-01-01
    • 1970-01-01
    • 2017-08-06
    • 1970-01-01
    • 2013-03-01
    • 2016-04-09
    • 1970-01-01
    相关资源
    最近更新 更多