gpt4 book ai didi

java - 使用 servlet 从 mysql 检索数据的空指针异常

转载 作者:行者123 更新时间:2023-11-29 15:25:17 24 4
gpt4 key购买 nike

我正在尝试从名为 id 的数据库中检索数据,它有 2 列 uname 和 pass。我相信我的bean类(学生)完全没问题,正如你所看到的,pol类用于与db交互,类dispach将数据发送到jsp,我的问题是,当我在服务器上运行dispach时,我得到NullPointerException

public class pol {

public List<student> getstudent() throws Exception {

List<student> students = new ArrayList<>();
String connectionURL = "jdbc:mysql://localhost:3306/pooya";

Connection connection = null;
Statement s = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");

connection = DriverManager.getConnection(connectionURL, "root", "");

String sql = "select * from id";

s = connection.createStatement();
s.executeQuery(sql);

rs = s.getResultSet();

while (rs.next()) {

String uname = rs.getString("uname");
String pass = rs.getString("pass");
student tempstudent = new student(uname, pass);
students.add(tempstudent);

}
return students;

} finally {
// close JDBC objects
close(connection, s, rs);
}
}

private void close(Connection connection, Statement s, ResultSet rs) {

try {
if (rs != null) {
rs.close();
}

if (s != null) {
s.close();
}

if (connection != null) {
connection.close(); // doesn't really close it ... just puts back in connection pool
}
} catch (Exception exc) {
exc.printStackTrace();
}
}
}

public class dispach extends HttpServlet {
private java java;
private pol pol;

@Resource(name = "jdbc/web_student_tracker")
private DataSource dataSource;

@Override
public void init() throws ServletException {
try {
java = new java(dataSource);
} catch (Exception exc) {
throw new ServletException(exc);
}
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
listteacher(request, response);
} catch (Exception e) {
e.printStackTrace();
}

}

private void listteacher(HttpServletRequest request, HttpServletResponse response) throws Exception {

List<student> student = pol.getstudent();
request.setAttribute("select", student);
//fix
RequestDispatcher dispatcher = request.getRequestDispatcher("/NewFile.jsp");

dispatcher.forward(request, response);
}
}

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table>
<c:forEach var="tempstudent" items="${select}">
<tr>
<td>${tempstudent.uname}</td>
</tr>
</c:forEach>
</table>
</body>
</html>

最佳答案

您正在使用pol这一行的成员变量List<student> student = pol.getstudent();dispatch#listteacher方法,但尚未初始化。您必须首先初始化它(在构造函数中或其他方式)才能调用它的方法,否则您确实会得到 NullPointerException .

还可以考虑将您的类命名为 kebab-cased,例如Dispatch而不是dispatch 。这就是 Java 类命名约定。

关于java - 使用 servlet 从 mysql 检索数据的空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59128762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com