池不在 servlet 中,但可以在独立应用中使用。
游泳池类在两种情况下很常见:
public class Pool {
private static DataSource ds;
static {
DriverAdapterCPDS cpds = new DriverAdapterCPDS();
try {
cpds.setDriver("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
cpds.setUrl("jdbc:mysql://localhost:3306/collage");
cpds.setUser("root");
cpds.setPassword("r00t");
SharedPoolDataSource tds = new SharedPoolDataSource();
tds.setConnectionPoolDataSource(cpds);
tds.setMaxTotal(10);
/*tds.setMaxWait(50);
tds.setMaxTotal();*/
tds.setMaxTotal(50);
ds = tds;
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
对于独立类,其工作方式如下
public class MainClass {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = Pool.getConnection();
// Do work with connection
statement = connection.createStatement();
String selectEmployeesSQL = "select * from students";
resultSet = statement.executeQuery(selectEmployeesSQL);
while (resultSet.next()) {
printTestTable(resultSet);
}
} catch (Exception e) {
e.printStackTrace();
} finnaly {
...
}
}
并且来自 servlet 的一部分如下:
@WebServlet("/Demo.do")
public class DemoController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ResultSet rsObj = null;
Connection connObj = null;
PreparedStatement pstmtObj = null;
try {
connObj = Pool.getConnection();
...
这里是例外”
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Servlet execution threw an exception
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
javax.servlet.ServletException: Servlet execution threw an exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.lang.NoClassDefFoundError: Could not initialize class am.ak.dao.jdbc.connections.Pool
test.DemoController.doGet(DemoController.java:27)
javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Note The full stack trace of the root cause is available in the server logs.
谢谢。
添加:
已解决:
所以错过了这两个库
有趣: 在POM中,我仅添加了一个依赖项机器人,它可以解决两个问题:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.5.0</version>
</dependency>