1

我想通过 JNDI 查找从 Servlet 到 JDBC 的对象。
这个过程的确切代码是什么?

4

2 回答 2

3

可能取决于您的 servlet 容器:

String initialContext = "java:comp/env";  
Context env = (Context) new InitialContext().lookup(initialContext);
Object o = env.lookup(name);
于 2009-06-05T07:44:21.857 回答
-1

在 try 块中使用此代码

Context initContext = new InitialContext();
Context envContext = (Context) 
initContext.lookup("java:comp/env");
DataSource ds = (DataSource) 
envContext.lookup("jdbc/UsersDB");
Connection connection = ds.getConnection();

在上下文中添加这个。xml

<Resource
    name="jdbc/UsersDB"
    auth="Container"
    type="javax.sql.DataSource"
    maxActive="100"
    maxIdle="30"
    maxWait="10000"
    driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver"
    url="jdbc:sqlserver://192.168.1.56:1433;DatabaseName=testdb1;"
    username="uname"
    password="pwd"
    />

web.xml

 <resource-ref>
    <description>DB Connection</description>
    <res-ref-name>jdbc/UsersDB</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>
于 2018-03-20T14:13:08.480 回答