开发者社区> 问答> 正文

使用tomcat数据源,提示没有绑定名称,为什么?

这是context里面的

<Context>
<ResourceLink global="mySource" name="mySource" type="javax.sql.DataSource"/>
<Resource name="mySource"
            auth="Container"
            type="javax.sql.DataSource"
            username="root"
            password="root"
            driverClassName="com.mysql.jdbc.Driver"
            url="jdbc:mysql:///day11"
            maxActive="8"
            maxIdle="4"/>
</Context>

这是web.xml里面的

 <resource-ref>
    <description>DB Connection</description>
    <res-ref-name>mySource</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>

代码是:

Context initCtx = new InitialContext();
Context jndi = (Context) initCtx.lookup("java:comp/env");
DataSource source = (DataSource) jndi.lookup("mySource");
Connection conn = source.getConnection();

报错信息:

screenshot

哪位大神知道这是怎么回事啊,该怎么解决啊

展开
收起
落地花开啦 2016-06-01 23:41:59 2546 0
1 条回答
写回答
取消 提交回答
  • 喜欢技术,喜欢努力的人

    web工程下的,WEB-INF下的web.xml添加这一段:

     <resource-ref>
        <description>DB Connection</description>
        <res-ref-name>JDBC/TestDB</res-ref-name>
        <res-type>javax.sql.DataSource</res-type>
        <res-auth>Container</res-auth>
      </resource-ref>

    相对应的jsp或者java代码应该为:

    DataSource ds = (DataSource) ctx.lookup("java:comp/env/JDBC/TestDB");

    或者

    Context envCtx = (Context) ctx.lookup("java:comp/env");
    DataSource ds = (DataSource) ctx.lookup("JDBC/TestDB");
    2019-07-17 19:23:51
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Apache Tomcat 的云原生演进 立即下载
低代码开发师(初级)实战教程 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载