java - Glassfish jdbc/数据库查找失败

标签 java servlets jdbc glassfish web.xml

我希望我不会因为找不到答案而提出重复的问题。 我收到此错误:

javax.naming.NamingException:在 SerialContext 中查找“jdbc/osclassDB”失败

这就是我所做的:我设置了一个 JDBC 连接池 和一个指向该池的 JDBC 资源(均在 Glassfish 中)。

然后我告诉我的 web.xml 有一个 JDBC 资源:

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

然后我尝试在 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

但是当我调用 Servlet 时,它会抛出 NamingException 并告诉我 在 SerialContext 中查找“jdbc/osclassDB”失败

我在这里做错了什么?是web.xml吗?我错过了什么? 感谢您的帮助!

最佳答案

解决问题:

第一,通过添加一个 sun-web.xml 来链接 web.xml 中的资源引用到一个实际的jndi-name(我在 Glassfish 上设置的)。通常情况下,这应该是没有必要的(甲骨文说),但我还是这么做了[编辑:事实证明,这确实没有必要! ]

第二我遗漏了“jdbc”。在 servletweb.xmlsun-web.xml 中,它现在被称为“osclassDB”(我的资源名称) “jdbc/osclassDB”

现在看起来像这样:

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> 

在 servlet 中

Context dbContext = (Context) initialContext.lookup("java:comp/env");
DataSource dataSource = (DataSource) dbContext.lookup("osclassDB");
connection = dataSource.getConnection();

[编辑:]sun-web.xml确实没有必要

关于java - Glassfish jdbc/数据库查找失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21137208/

相关文章:

java - DynamoDB Spring Boot 数据剩余 "PersistentEntity must not be null!"

java - 在Hadoop的Reducer中获取整数数组

java - 根据请求的主机名在 JBoss 中配置多个 keystore

java - 如何在低(汇编)级别捕获和处理异常?

java - Ajax HTTPServlet 请求不会将信息从 ajax 传递到 Controller

java - 如何在没有 ArrayIndexOutOfBoundsException 的情况下通过 executeBatch 获取生成的 key ?

java - 在 MVC webapp 中使用 JSP 和 Servlet 的最佳方式

jakarta-ee - 上传到地方

java - ResultSet.TYPE_FORWARD_ONLY 可以向后滚动

java - ORA-01810 : format code appears twice : jdbctemplate