views:

233

answers:

2

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?

+3  A: 

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");
Bozho
I'm sort of new to Java web apps... could you explain please?
titaniumdecoy
Also, this is not in my JSP file, it is in my bean (i.e., Java class) file.
titaniumdecoy
see my update for the JNDI. if you want to use the `@Resource` annotation you need to have someone to read it. JSP itself cannot read it.
Bozho
new `InitialContext()` (my updated answer)
Bozho
Thanks for your help. I tried this method (replacing the parameter to lookup with "jdbc/myDS") but I get an error: javax.naming.NameNotFoundException: Name jdbc is not bound in this Context
titaniumdecoy
sorry, I forgot one detail. Check my update.
Bozho
Now your solution works too. :)
titaniumdecoy
+1  A: 

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

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