Getting DataSource resource in a Java web app

孤街浪徒 提交于 2019-12-12 20:46:46

问题


I have the following resource tag in my context.xml file:

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

I am developing a Java web app using the Stripes framework in NetBeans.

How can I get this resource from within a Java class?


回答1:


You need your bean to be instantiated by something (a dependecy injection framework) which knows how to handle the @Resrouce annotation. JSP itself doesn't know how.

In this case it would be simpler to locate the DataSource in the JNDI context:

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



回答2:


Thank you Bozho for the answer. I only had to change the lookup string to get it to work:

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


来源:https://stackoverflow.com/questions/2242980/getting-datasource-resource-in-a-java-web-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!