3 回答
TA贡献1813条经验 获得超2个赞
如果您的 users 表中有超过 1 个具有不同角色的用户,则您的 checkRole() 方法将始终评估为 true。因为您要选择字段角色属于特定类型的所有行。如果您的用户表中存在特定的角色类型,它将始终为真...
就像已经提到的另一个答案一样,您需要传递一个唯一标识符。查询应该如何知道您正在检查哪个用户的角色?在大多数应用程序中,这是由 user_id/id 字段完成的,但由于您在这里只有电子邮件,因此您也可以使用它。我会做这样的事情:
public static boolean isAdmin(String email) {
boolean check = false;
PreparedStatement pst = null;
ResultSet rs = null;
try(Connection conn= ConnectionConfiguration.getConnection()){
pst = conn.prepareStatement("SELECT * FROM users WHERE email =? and role='admin';");
pst.setString(1, email);
rs = pst.executeQuery();
check = rs.next(); // if the resultSet has results, then check will evaluate to true
} catch (SQLException e) {
e.printStackTrace();
}
return check;
}
然后对于您的 servlet:
{
String pass1 = request.getParameter("password");
String email = request.getParameter("email");
//first check if valid login details (seperate it out so you can be more specific in the error you give back, and you don't have to repeat yourself)
if(User.validate(email,pass1)){
// s.invalidate(); //this isn't really necessary here, normally you invalidate the session variables when the user logs out. If a different user logs in (whilst one is already logged in), then any session variables you have set would override it.
String url = "/RegularUser.jsp";
String role = "regular";
//now check if user is admin
if(User.isAdmin(email)){
url = "/Admin.jsp"
role = "admin";
}
//set your session variables
//s.setAttribute("user_email", email);
//s.setAttribute("user_role", role);
forwardTo(ctx, request, response, url);
}else{
//wrong login details - set values back in form
request.setAttribute("email",email);
request.setAttribute("pass", pass1);
forwardTo(ctx, request, response, "/Login.jsp");
}
}
TA贡献1779条经验 获得超6个赞
在 checkRole() 方法中,您需要在找到管理员后跳出 while 循环,否则您的“find”布尔值可能会在下一次迭代中再次设置为 false。
TA贡献1862条经验 获得超7个赞
更改您的 checkRole 方法,例如
public static boolean checkRole(String email) {
boolean find = false;
PreparedStatement pst = null;
ResultSet rs = null;
try(Connection conn= ConnectionConfiguration.getConnection()){
pst = conn.prepareStatement("SELECT * FROM users WHERE email =? and role='admin';");
pst.setString(1, email);
rs = pst.executeQuery();
if(rs.next()) {
find = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return find;
}
并在您的 servlet 代码中编写 if 条件如下
if(User.validate(email,pass1) && User.checkRole(email))
添加回答
举报