java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp.BasicDataSource cannot be cast to org.apache.tomcat.jdbc.pool.DataSource

只谈情不闲聊 提交于 2019-12-03 16:13:46
ftfarias

In my case I just forgot to put:

factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"

in my /tomcat7/conf/context.xml. Just added and all worked fine.

My context.xml:

<Context> 
    <Resource name="jdbc/gestrel" auth="Container"
    type="javax.sql.DataSource"
    driverClassName="org.postgresql.Driver"
    url="jdbc:postgresql://127.0.0.1:5432/g...."
    username="postgres"
    password="....." maxActive="20" maxIdle="10"
    factory="org.apache.tomcat.jdbc.pool.DataSourceFactory"
   maxWait="-1"/>
</Context>

Today I've spent a half of the day trying to deal with the similar issue. I have tomcat server.xml file defining context like this:

<Context docBase="app" path="/my_context_path">
</Context>

Then I tried to add jdbc pool support using org.apache.tomcat.jdbc.pool.DataSource.

Just added resource definition to my server.xml context definition (see above). And of cause I defined resource-ref in my web.xml.

But there was always org.apache.tomcat.dbcp.dbcp.BasicDataSource returned. I spent time debugging tomcat and finally got to the following:

  1. If I define resource in server.xml context - tomcat does NOT pick that up.
  2. If define in web archive's META-INF/context.xml works ok.
  3. If define in server.xml GlobalNamingResources tag - tomcat does NOT pick that up.
  4. If define in tomcat global context.xml file works ok.

If you specify resource-ref in web.xml for bad cases 1,3 - tomcat will return org.apache.tomcat.dbcp.dbcp.BasicDataSource, cause as I can see it is some kind of default. BUT using such data source returned will cause something like this:

org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null' at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1452) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371) at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)

If not specify resource-ref in web.xml then you will get an exception telling that resource with such name could not be find.

Also I noticed that for good cases 2,4 specifying resource-ref in web.xml is not necessary (works with and without resource-ref).

Try some of the cases I described. I hope something will help.

I would try to define resource in tomcat global context.xml file.

Good luck!

P.s. I run 7.0.22 version as well.

The solution is to import javax.sql.DataSource in your servlet as you define the resouce in context.xml of type="javax.sql.DataSource"

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