关于WEB项目中访问连接池的问题
最近学习做了一个简单的WEB项目,遇到一个难题,在管理页面中创建了一个连接池,从数据库里看连接也是成功的,但是在其它类中获取连接总是提示异常,哪位高手给帮忙看一下
这是连接池
public final class ConnectionPoolInit {
private static BasicDataSource basicDataSource = null;
private ConnectionPoolInit(){}
public static void createDataSource() throws Exception{
Properties properties = new Properties();
InputStream inputStream = ConnectionPoolInit.class.
getClassLoader().getResourceAsStream("dbcpconfig.properties");
properties.load(inputStream);
basicDataSource = (BasicDataSource) BasicDataSourceFactory.createDataSource(properties);
}
public static Connection getConnection() throws Exception{
return basicDataSource.getConnection();
}
这是获得连接
public UserBean loginControl(String uid,String pwd) throws Exception{
UserBean userBean = new UserBean();
connection = ConnectionPoolInit.getConnection();
这是返回异常
严重: Servlet.service() for servlet [LoginServlet] in context with path [/chart] threw exception [org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper cannot be cast to org.apache.tomcat.dbcp.dbcp.BasicDataSource] with root cause
javax.servlet.ServletException: org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper cannot be cast to org.apache.tomcat.dbcp.dbcp.BasicDataSource
------解决方案--------------------public final class ConnectionPoolInit {
private static BasicDataSource basicDataSource = null;
static{
if(basicDataSource == null)
{
Properties properties = new Properties();
InputStream inputStream = ConnectionPoolInit.class.
getClassLoader().getResourceAsStream("dbcpconfig.properties");
properties.load(inputStream);
basicDataSource = (BasicDataSource) BasicDataSourceFactory.createDataSource(properties);
}
}
public static synchronized Connection getConnection() throws Exception{
return basicDataSource.getConnection();
}
}
帮你改造了下,调用:ConnectionPoolInit.getConnection();注意红色的同步关键字必须加上。
------解决方案--------------------和一楼的差不多,也帮楼主该了一下代码:
public final class ConnectionPoolInit {
private static BasicDataSource basicDataSource = null;
static{
Properties properties = new Properties();
InputStream inputStream = ConnectionPoolInit.class.
getClassLoader().getResourceAsStream("dbcpconfig.properties");
properties.load(inputStream);
basicDataSource = (BasicDataSource) BasicDataSourceFactory.createDataSource(properties);
}
private ConnectionPoolInit(){}
public static void createDataSource() throws Exception{
return basicDataSource
}
public static Connection getConnection() throws Exception{
return basicDataSource.getConnection();
}
}
用楼主的方法时过前台管理页面访问servlet来初始化连接的是可以的,是因为创建的数据库连接池,如果启动服务后,从来没有访问那个servlet页面,访问其他的方法中只包含:ConnectionPoolInit.getConnection();是肯定会报错的,因为还没有初始化连接池。
分析的不一定对,楼主可以试试