我为这个错误找到的解决方案是“通过构建路径添加 jar 文件”和“将包含驱动程序的 jar 文件放在 WEB-INF/lib 中”(以及类似的公式),但我已经尝试了其中的两个。
回到我的问题。这是我的代码:
jsp文件
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ page import="db.DBAccess" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Insert title here</title>
</head>
<body>
<jsp:useBean id="dba" class="db.DBAccess"></jsp:useBean>
<jsp:setProperty name="dba" property="selection" value="s" />
</body>
</html>
爪哇豆
package db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBAccess {
public DBAccess() {
}
private String selection = "";
public void setSelection(String s) {
final String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/test";
String user = "user1";
String pswd = "user1pswd";
Connection con = null;
Statement stmt = null;
try {
// initialize connection
Class.forName(driver);
con = DriverManager.getConnection(url, user, pswd);
stmt = con.createStatement();
// execute select
ResultSet results = stmt.executeQuery("SELECT * FROM t");
results.next();
selection = results.getString(1);
// close connection
stmt.close();
con.close();
} catch (ClassNotFoundException cnfe) {
System.out.println(cnfe.toString());
} catch (SQLException e) {
System.out.println(e.toString());
}
}
}
t 的内容是一列,标签为“string”,内容为“hello world”
即使我正确链接了 jar 文件,为什么还会出现此异常?