【发布时间】:2021-07-24 08:13:35
【问题描述】:
我有一个 SQL 表,其中存储用户、密码和用户角色/权限级别,Admins=5,普通用户=1。现在,我不确定如何将从我的 getUserRole 方法获得的信息传递给登录事件处理程序,因为它是一个 Int 方法,你不能从一个 int 返回一个布尔类型变量,或者有更好的如何重新编写代码以使其更简单?
登录方式
public boolean isLogin(String user, String pass) throws Exception{
PreparedStatement pr = null;
ResultSet rs = null;
String sql = "SELECT * FROM Login where username = ? and password = ?";
try{
pr = this.connection.prepareStatement(sql);
pr.setString(1, user);
pr.setString(2, pass);
rs = pr.executeQuery();
if(rs.next()){
rs.getInt("role");
return true;
}
return false;
}
catch(SQLException ex){
return false;
}
finally{
pr.close();
rs.close();
}
}
获取用户权限方法
public int getUserRole(String user) throws Exception
{
PreparedStatement pr = null;
ResultSet rs = null;
String sql = "SELECT * FROM Login WHERE username = ? AND role = ?";
try
{
pr = this.connection.prepareStatement(sql);
pr.setString(1, user);
if(rs.next())
{
int role = rs.getInt("role");
return role;
}
else{
return 0;
}
}
catch(SQLException ex)
{
return 0;
}
finally
{
pr.close();
rs.close();
}
}
最后是控制器,登录事件处理程序
@FXML
public void Login (ActionEvent event){
try{
if(this.loginModel.isLogin(this.username.getText(), this.password.getText())){
Stage stage = (Stage) this.login.getScene().getWindow();
stage.close();
if(this.loginModel.getUserRole(this.username.getText()))//error is here,
cant get username as its a boolean type and not int
}
}
catch (Exception localException)
{
this.loginStatus.setText("The username or password entered is incorrect. Please check and try again.");
}
}
【问题讨论】: