将数据库逻辑与servlet分离是很重要的,它使管理更加容易。为数据库连接创建单独的类也很有用。之所以没有得到任何结果,是因为在UserDAO类中,没有从结果集中获得任何结果。
为数据库连接创建一个类。我们可以随时调用这个数据库。
public class DBConnection {
private static String url = null;
private static Connection conn = null;
public static Connection getConnection(){
try{
Class.forName("com.mysql.jdbc.Driver");
url = "jdbc:mysql://localhost:3306/usuarios";
conn = DriverManager.getConnection(url,"root","admin");
} catch (Exception e) {
System.out.println(e);
}
return conn;
}
}
以及我们的userdao类的adminpanel方法:
//Now we can use this like this, i looked at your code and saw you wanted to have a list of UserBean objects.. we can do that like this:
public List<UserBean> adminPanel(){
ArrayList<UserBean> users = new ArrayList<UserBean>();
//get connection from our DBConneciton class we created earlier
try(Connection conn= DBConnection.getConnection()){
//create our sql statement
PreparedStatement pst = conn.prepareStatement("select firstname,lastname,username,tipo from idusuario;");
//execute query
pst.executeQuery();
//now get results
ResultSet rs = pst.executeQuery();
//while ResultSet has results
while (rs.next()) {
//create new user object to hold the info in
UserBean user = new UserBean();
//get the results from resultset
String firstname = rs.getString(1);
String lastname = rs.getString(2);
String username = rs.getString(3);
int type = rs.getInt(4);
//set results to user object
user.setFirstName(firstname);
user.setLastName(lastname);
user.setUserName(username);
user.setType(type);
users.add(user); //add userobject to list of userobjects
}
} catch (SQLException e) {
e.printStackTrace();
}
//we don't need to close our db connection because the try statement does it for us
return users; //return list of users
}
现在要访问这些,我们在servlet中需要做的就是:
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
UserDAO u = new UserDAO(); //instantiate class
//get our list of users
List<UserBean> users = u.adminPanel();
//set our list to request
request.setAttribute("memberList", users);
//forward to jsp page
RequestDispatcher rs = request.getRequestDispatcher("AdminPanel.jsp");
rs.forward(request, response);
}
你的JSP上的一切看起来都很好,所以应该可以工作,如果你有任何问题或问题,请告诉我。
编辑:
一些调试思路:
在servlet中,这样做可以查看用户列表有多大:
...
//get our list of users
List<UserBean> users = u.adminPanel();
//check if we are actually getting something from the database
System.out.println(users.size());
如果大小为0,则表示我们的查询有问题。如果使用以下查询手动查询数据库,请检查是否从数据库中获取任何信息:
select firstname,lastname,username,tipo from idusuario;
编辑2
尝试删除
<c:out tags:
<c:forEach var="row" items="${memberList}">
<tr>
<td>${row.firstname}</td>
<td>${row.lastname}</td>
<td>${row.username}</td>
<td>${row.type}</td>
<td><a href="AdminPanel.jsp" name="Edit">Habilitar usuario</a> </td>
</tr>
</c:forEach>