在web.xml中没有resource-ref的情况下连接数据源

时间:2013-08-01 21:17:24

标签: java tomcat jdbc datasource

我在tomcat7上运行了一个Web应用程序。 tomcat7和全局数据源配置组件是jetty门户的一部分。现在,我可以在门户上设置全局数据源,将其作为ResourceLink添加到context.xml(我的应用程序在tomcat上)。我想知道是否有办法通过我的应用程序jdbc代码连接到这些数据源,而无需在我的web.xml中放入resource-ref。

(这将帮助我连接到新的数据源名称,而无需重新部署我的WAR文件,只是为了添加新的resource-ref标签)

2 个答案:

答案 0 :(得分:4)

如果您使用的是Apache Tomcat 7,则可以在servlet中使用@Resource来注入数据源。

将文件context.xml添加到项目本地的META-INF目录中:

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

在servlet中:

@WebServlet(urlPatterns = { "/" }, loadOnStartup = 0)
public class TestServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Resource(name = "jdbc/test")
    private DataSource ds;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
            throws ServletException, IOException {
        resp.setContentType("text/plain");
        try (Connection conn = ds.getConnection(); 
             PrintWriter out = resp.getWriter();) {
            out.println(conn.getMetaData().getDatabaseProductName());
            out.println(conn.getMetaData().getDatabaseProductVersion());
        } catch (SQLException e) {
            log(e.getMessage(), e);
        }
    }

}

WAR结构如下:

C:.
+---META-INF
|       context.xml
|       MANIFEST.MF
|
\---WEB-INF
    +---classes
    |   \---test
    |           TestServlet.class
    |
    \---lib
            mysql.jar

浏览器http://localhost:8080/Test/中的输出:

MySQL
5.5.32

答案 1 :(得分:0)

似乎这样可行。由于我的上下文没有正确刷新,我在完成这项工作时遇到了问题。 重新部署后,在上下文中正确设置了ResourceLink,并且webapp能够执行JNDI查找并连接到数据源。

相关问题