我正在尝试从名为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类的命名约定。