当我运行NullPointerException
时,我不断收到userList.jsp
错误:
我试图输出用户对象的数组列表的大小:
<%--
Document : userList
Created on : 13-Mar-2019, 22:08:54
Author : sonia
--%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="com.mycompany.gartisweb.domain.User"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% ArrayList users = (ArrayList)request.getAttribute("users"); %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>List of Users</title>
</head>
<body>
<% users.size(); %>
</body>
</html>
这是我的servlet类的样子:
public class UserListServlet extends HttpServlet {
public UserListServlet() {
}
//private final UserDao ud = new UserDao();
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// List<User> users = new ArrayList();
// users = ud.findAllUsers();
request.setAttribute("users", new UserDao().findAllUsers());
ServletContext servletContext = getServletContext();
RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher("userList.jsp");
//RequestDispatcher rd = request.getRequestDispatcher("userList.jsp");
requestDispatcher.forward(request, response);
//rd.forward(request, response);
}
UserDao类中的findAllUsers():
@Override
public ArrayList<User> findAllUsers() {
ArrayList<User> userList = new ArrayList<>();
Connection con;
con = DBConnection.createConnection();
Statement statement = null;
ResultSet rs;
try {
con.setAutoCommit(false);
statement = con.createStatement();
rs = statement.executeQuery("SELECT * FROM user");
while (rs.next()) {
User user = new User();
user.setId(rs.getInt(1));
user.setEmail(rs.getString(2));
user.setPassword(rs.getString(3));
user.setFirstName(rs.getString(4));
user.setSurName(rs.getString(5));
user.setRole(rs.getString(6));
userList.add(user);
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException ex) {
throw new RuntimeException(ex);
}
}
}
return userList;
}
我在代码中找不到错误,是否有人可以向我解释如何解决此问题?
那是因为您使用http://.../userList.jsp
URL直接访问JSP。使用映射到UserListServlet
的URL,以便servlet可以设置变量并执行转发。
你也可能想做<%= users.size(); %>
来显示用户数。