在Java Web应用程序中获取DataSource资源 [英] Getting DataSource resource in a Java web app

查看:521
本文介绍了在Java Web应用程序中获取DataSource资源的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的context.xml文件中具有以下资源标记:

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>

我正在使用NetBeans中的Stripes框架开发Java Web应用程序.

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

如何从Java类中获取此资源?

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

推荐答案

您需要使用知道如何处理@Resrouce批注的某种东西(一个依赖注入框架)来实例化您的bean. JSP本身不知道如何.

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.

在这种情况下,在JNDI上下文中定位数据源会更简单:

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");

这篇关于在Java Web应用程序中获取DataSource资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆