java - 根据输入字段分解错误消息

标签 java javafx

我有 3 个输入字段:用户名、密码和类型。

如果这 3 个错误中的任何一个不正确,我只会收到 1 条错误消息,其中指出“用户名和密码不正确”。

如何分解错误消息,以便它显示密码、用户名或类型的值是否输入错误。

这些是我使用的 2 个文件:登录模型和登录 Controller 。顺便说一句,下面的代码没有错误。

它工作得很好。我只是想扩展它来分解错误消息。

登录 Controller 文件:

public class LoginController implements Initializable {

    /**
     * Initializes the controller class.
     */
    public LoginModel loginModel = new LoginModel();   
    @FXML private Label isConnected;
    @FXML private JFXTextField txtUsername;
    @FXML private JFXPasswordField txtPassword;
    @FXML private ComboBox<String> comboType;

    ObservableList<String> list = FXCollections.observableArrayList("admin", "manager", "clerk");

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        comboType.setItems(list);
        if(loginModel.isDbConnected()) {
            isConnected.setText("Connected");
        }
        else {
            isConnected.setText("Not Connected");
        }
    }

    public void Login (ActionEvent event) {
        try {
            if(loginModel.isLogin(comboType.getValue(), txtUsername.getText(), txtPassword.getText())) {
                isConnected.setText("usern & pass is correct");

                //closes login fxml file
                ((Node)event.getSource()).getScene().getWindow().hide();

                //loads main interface fxml file
                Stage primaryStage = new Stage();
                FXMLLoader loader = new FXMLLoader();
                Pane root = loader.load(getClass().getResource("/gui/uicomponents/Main.fxml").openStream()); 
                MainController mainController = (MainController)loader.getController();
                mainController.getUser("Hi " + txtUsername.getText());
                Scene scene = new Scene(root);
                scene.getStylesheets().add(getClass().getResource("/resources/css/Consolidated.css").toExternalForm());
                primaryStage.setMaximized(true);
                primaryStage.setTitle("Main Interface");
                primaryStage.setScene(scene);
                primaryStage.show(); 
            }
            else {
                isConnected.setText("usern & pass is not correct");
            }
        } catch (SQLException ex) {
            isConnected.setText("usern & pass is not correct");  
            Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }      
}

登录模型文件:

public class LoginModel {
    Connection connection;
    public LoginModel() {
        connection = SqliteConnection.Connector();
        if(connection == null) {
            System.out.println("Connection to DB Failed");
            System.exit(1);          
        }
    }

    public boolean isDbConnected() {
        try {
            return !connection.isClosed();
        } catch (SQLException ex) {
            Logger.getLogger(LoginModel.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }
    }

    public boolean isLogin(String type, String user, String pass) throws SQLException {
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        String query = "select * from users where type = ? and username = ? and password = ?";
        try {
            preparedStatement = connection.prepareStatement(query);
            preparedStatement.setString(1, type);
            preparedStatement.setString(2, user);
            preparedStatement.setString(3, pass);       
            resultSet = preparedStatement.executeQuery();

            //if returns result from db
            if(resultSet.next()) {
                return true;
            }
            else {
                return false;
            }
        }
        catch(Exception e) {
            System.out.println(e);
            return false;            
        }
        finally {
            preparedStatement.close();
            resultSet.close();
        }
    }
}

最佳答案

从安全角度来看,揭示哪部分详细信息不正确并不是一个好的做法,也就是说,它会使您的应用程序更容易受到黑客的攻击,因为您给出了更多提示: 用户 ID 是否不正确,或者密码不正确,或者类型不正确。

但是,如果您确实想根据自己的项目要求显示非常具体的错误消息,则可以通过检查 TypeUserName 是否存在来实现然后定义并抛出自定义异常,例如 TypeNotFoundExceptionUserNameNotFoundException 异常,如下所示:

Login()方法:

public void Login (ActionEvent event) {
        try {
            if(loginModel.isLogin(comboType.getValue(), 
                 txtUsername.getText(), txtPassword.getText())) {
                //add your code
            }
            else {
                isConnected.setText(" pass is not correct");
            }
        } catch (TypeNotFoundException ex) {
            isConnected.setText("Type is not correct");  
            //add your logger      
     } catch (UserNameNotFoundException ex) {
         isConnected.setText("Username is not correct");  
          //add your logger
        } catch (SQLException ex) {
           isConnected.setText("technical problem,please try after some time");  
           //add your logger
        } catch (IOException ex) {
          //add your logger
        }
    }

isLogin():

public boolean isLogin(String type, String user, String pass) throws SQLException {
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        String query = "select * from users where type = ? 
            and username = ? and password = ?";
        try {
           //other code

            //if returns result from db
            if(resultSet.next()) {
                return true;
            }
            else {
                //String typeQuery = "select * from users where type = ?";
                //Execute the typeQuery and throw TypeNotFoundException

                //String userNameQuery = "select * from users where username = ?";
                //Execute the userNameQuery and throw UserNameNotFoundException

                return false;
            }
        } //other code as is
    }

关于java - 根据输入字段分解错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42873336/

相关文章:

java - 线程 "main"java.lang.NoClassDefFoundError : rpc/Stub 中出现异常

JavaFX 将事件监听器附加到黑色圆圈

JavaFX 导出和 VM 参数

javafx.scene.layout.Pane 无法转换为 javafx.fxml.FXMLLoader

java - 如何在 JUnit 中捕获异常

JavaFx:组合框最大宽度

JavaFX:显示时动态更新菜单

java - 使用 javafx 从 webview 获取内容

java - 根据Java中的天数获取日期

java - Android 我的第一个应用程序教程 android :onClick issues