3 回答

TA貢獻(xiàn)1813條經(jīng)驗(yàn) 獲得超2個(gè)贊
如果您的 users 表中有超過(guò) 1 個(gè)具有不同角色的用戶,則您的 checkRole() 方法將始終評(píng)估為 true。因?yàn)槟x擇字段角色屬于特定類型的所有行。如果您的用戶表中存在特定的角色類型,它將始終為真...
就像已經(jīng)提到的另一個(gè)答案一樣,您需要傳遞一個(gè)唯一標(biāo)識(shí)符。查詢應(yīng)該如何知道您正在檢查哪個(gè)用戶的角色?在大多數(shù)應(yīng)用程序中,這是由 user_id/id 字段完成的,但由于您在這里只有電子郵件,因此您也可以使用它。我會(huì)做這樣的事情:
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;
}
然后對(duì)于您的 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貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
在 checkRole() 方法中,您需要在找到管理員后跳出 while 循環(huán),否則您的“find”布爾值可能會(huì)在下一次迭代中再次設(shè)置為 false。

TA貢獻(xiàn)1862條經(jīng)驗(yàn) 獲得超7個(gè)贊
更改您的 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 代碼中編寫(xiě) if 條件如下
if(User.validate(email,pass1) && User.checkRole(email))
添加回答
舉報(bào)