簡體   English   中英

在Java Web應用程序中獲取DataSource資源

[英]Getting DataSource resource in a Java web app

我的context.xml文件中有以下資源標記:

<?xml version="1.0" encoding="UTF-8"?>
<Context antiJARLocking="true" path="/myApp">
  <Resource name="jdbc/myDS" auth="Container" 
    type="javax.sql.DataSource" maxActive="100" maxIdle="30" maxWait="1000"
    username="user" password="passwd"
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/myDB" />
</Context>

我正在使用NetBeans中的Stripes框架開發Java Web應用程序。

如何從Java類中獲取此資源?

您需要使用知道如何處理@Resrouce批注的某種東西(一個依賴注入框架)來實例化bean。 JSP本身不知道如何。

在這種情況下,在JNDI上下文中定位數據源會更簡單:

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

謝謝博zh的回答。 我只需要更改查找字符串即可使其工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM