如何在 JAX-RS (Jersey) 应用程序中使用 JNDI 资源?

发布于 2024-12-13 03:14:02 字数 1169 浏览 0 评论 0原文

我正在尝试通过 Tomcat JNDI 资源建立与数据库的连接。今天看了很多文章,似乎没有找到答案。

在我的 server.xml 中,我有:

  <GlobalNamingResources>
  <Resource name="jdbc/MyDB" auth="Container" type="javax.sql.DataSource"
      maxActive="100" maxIdle="30" maxWait="10000"
      username="tomcat" password="...."
      driverClassName="com.mysql.jdbc.Driver"
      url="jdbc:mysql://localhost:3333/tomcat?autoReconnect=true"/>

  .....
  </GlobalNamingResources>

在我的 Web 服务中,我尝试通过以下方式访问资源:

    InitialContext ctx = new InitialContext();
    DataSource data = (DataSource)ctx.lookup("java:comp/env/jdbc/MyDB");
    Connection conn = data.getConnection();

当我运行代码时,出现此异常:

Nov 2, 2011 1:06:20 PM com.sun.jersey.spi.container.ContainerResponse  mapMappableContainerException
SEVERE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container
javax.naming.NameNotFoundException: Name jdbc is not bound in this Context
...

我有最新的 mysql-connector-java-5.1.18-bin .jar 在我的网络应用程序的库和我的 tomcat 库中。

你能帮我让它工作吗?

I'm trying to set up a connection to my database through a Tomcat JNDI resource. I've been looking at many articles today and I can't seem to find an answer.

In my server.xml I have:

  <GlobalNamingResources>
  <Resource name="jdbc/MyDB" auth="Container" type="javax.sql.DataSource"
      maxActive="100" maxIdle="30" maxWait="10000"
      username="tomcat" password="...."
      driverClassName="com.mysql.jdbc.Driver"
      url="jdbc:mysql://localhost:3333/tomcat?autoReconnect=true"/>

  .....
  </GlobalNamingResources>

In my web service, I attempt to access the resource with:

    InitialContext ctx = new InitialContext();
    DataSource data = (DataSource)ctx.lookup("java:comp/env/jdbc/MyDB");
    Connection conn = data.getConnection();

When I run the code, I get this exception:

Nov 2, 2011 1:06:20 PM com.sun.jersey.spi.container.ContainerResponse  mapMappableContainerException
SEVERE: The exception contained within MappableContainerException could not be mapped to a response, re-throwing to the HTTP container
javax.naming.NameNotFoundException: Name jdbc is not bound in this Context
...

I have the newest mysql-connector-java-5.1.18-bin.jar in both my web-app's lib and my tomcat lib.

Can you please help me get this working?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

战皆罪 2024-12-20 03:14:02

我使用此代码,仅包含资源名称,并且它有效:

private Connection getConnection(){
      final Context ctx = new InitialContext();
      final DataSource ds = (DataSource) ctx.lookup("jdbc/MyDB");
      if (ds != null)
      {
             return ds.getConnection();
      }
      else
      {

      }
}

I use this code, with only the name of the resource, and it works:

private Connection getConnection(){
      final Context ctx = new InitialContext();
      final DataSource ds = (DataSource) ctx.lookup("jdbc/MyDB");
      if (ds != null)
      {
             return ds.getConnection();
      }
      else
      {

      }
}
人事已非 2024-12-20 03:14:02

我们只需要在java:之后提及jndi名称
在您的情况下:

InitialContext ctx = new InitialContext();
DataSource data = (DataSource)ctx.lookup("java:/jdbc/MyDB");
Connection conn = data.getConnection();

因为您在 server.xml 中配置如下:

<GlobalNamingResources>
  <Resource name="jdbc/MyDB" auth="Container" type="javax.sql.DataSource"
      maxActive="100" maxIdle="30" maxWait="10000"
      username="tomcat" password="...."
      driverClassName="com.mysql.jdbc.Driver"
      url="jdbc:mysql://localhost:3333/tomcat?autoReconnect=true"/>

  .....
  </GlobalNamingResources>

We just need to mention the jndi name after java:
In your case:

InitialContext ctx = new InitialContext();
DataSource data = (DataSource)ctx.lookup("java:/jdbc/MyDB");
Connection conn = data.getConnection();

Because you configured in your server.xml as below:

<GlobalNamingResources>
  <Resource name="jdbc/MyDB" auth="Container" type="javax.sql.DataSource"
      maxActive="100" maxIdle="30" maxWait="10000"
      username="tomcat" password="...."
      driverClassName="com.mysql.jdbc.Driver"
      url="jdbc:mysql://localhost:3333/tomcat?autoReconnect=true"/>

  .....
  </GlobalNamingResources>
一笔一画续写前缘 2024-12-20 03:14:02

我的解决方案是切换到数据库信息的属性文件,然后将其与实体管理器一起使用。

import java.io.FileReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;

import org.eclipse.persistence.config.EntityManagerProperties;
import org.eclipse.persistence.config.PersistenceUnitProperties;

...

        Properties properties = new Properties();
        FileReader fr = new FileReader(Constants.Config.getPropertiesFile());
        properties.load(fr);


        // connect to the database
        Map<String,String> emMap = new HashMap<String,String>();
        emMap.put(PersistenceUnitProperties.APP_LOCATION, Constants.Config.getAppDir());        
        emMap.put(EntityManagerProperties.JDBC_USER, properties.getProperty("db.username"));
        emMap.put(EntityManagerProperties.JDBC_PASSWORD, properties.getProperty("db.password"));
        // iterate over these properties attempting to read them in and connect to the url
        List<?> dbProps = Collections.list(properties.keys());
        Collections.sort(dbProps, new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                return o1.toString().compareTo(((String)o2));
            }
        });

        for(Object propKey : dbProps){
            // support multiple database key/values in the eform db.url, db.url1, ...  db.urlN
            if(!propKey.toString().matches("db.url\\d*")){
                continue;
            }
            String dbLocation = properties.getProperty(propKey.toString());
            try {
                if(dbLocation == null) continue;

                emMap.put(EntityManagerProperties.JDBC_URL, dbLocation);
                EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("db", emMap);
                em = entityManagerFactory.createEntityManager();
                // ensure we're connected by executing a no-op query
                em.createNativeQuery("select current_database()").getSingleResult(); // will only work for postgresql
                properties.put("db.connected", dbLocation);
                break;
              }
              catch (javax.persistence.PersistenceException e) {
                Utility.logger(DataHolder.class).error("Couldn't connect to " + dbLocation);
              }
        }

My solution was to switch to a properties file for the database information and then utilize it with entity manager.

import java.io.FileReader;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.servlet.ServletException;

import org.eclipse.persistence.config.EntityManagerProperties;
import org.eclipse.persistence.config.PersistenceUnitProperties;

...

        Properties properties = new Properties();
        FileReader fr = new FileReader(Constants.Config.getPropertiesFile());
        properties.load(fr);


        // connect to the database
        Map<String,String> emMap = new HashMap<String,String>();
        emMap.put(PersistenceUnitProperties.APP_LOCATION, Constants.Config.getAppDir());        
        emMap.put(EntityManagerProperties.JDBC_USER, properties.getProperty("db.username"));
        emMap.put(EntityManagerProperties.JDBC_PASSWORD, properties.getProperty("db.password"));
        // iterate over these properties attempting to read them in and connect to the url
        List<?> dbProps = Collections.list(properties.keys());
        Collections.sort(dbProps, new Comparator<Object>() {
            @Override
            public int compare(Object o1, Object o2) {
                return o1.toString().compareTo(((String)o2));
            }
        });

        for(Object propKey : dbProps){
            // support multiple database key/values in the eform db.url, db.url1, ...  db.urlN
            if(!propKey.toString().matches("db.url\\d*")){
                continue;
            }
            String dbLocation = properties.getProperty(propKey.toString());
            try {
                if(dbLocation == null) continue;

                emMap.put(EntityManagerProperties.JDBC_URL, dbLocation);
                EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("db", emMap);
                em = entityManagerFactory.createEntityManager();
                // ensure we're connected by executing a no-op query
                em.createNativeQuery("select current_database()").getSingleResult(); // will only work for postgresql
                properties.put("db.connected", dbLocation);
                break;
              }
              catch (javax.persistence.PersistenceException e) {
                Utility.logger(DataHolder.class).error("Couldn't connect to " + dbLocation);
              }
        }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文