如何将我的 servlet 连接到另一个 class 的布尔方法?

How to connect my servlet to the boolean method from another class?

我尝试了一些变体,我当然导入了 class,它包含我在我的 Servlet 中使用的布尔方法,但无论如何它都看不到该方法。

这是我 class logIN 中的方法:


        MyCon = Database.getConnection();
        boolean result = false;
        Statement statement = null;
        ResultSet resultSet = null;



        try {
            String sql = "SELECT * FROM input_form WHERE username ='"+username+"'AND password='"+password+"'";
            statement=MyCon.createStatement();
            resultSet = statement.executeQuery(sql);
            if (resultSet.next()) {
                result=true;
            }else {
                result = false;

            }
        } catch (SQLException e) {



        }
        return result;


    }

} ```

And when i need to access that method in servlet, it doesnt see it :

 ```protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        response.setContentType("text/html/charset-UTF-8");
        out =response.getWriter();

        boolean login = processLogin(username,password);  //this is where it doesnt see it

         ```

what could i do for my servlet to see the method?

创建您需要调用的 class 的 object,然后使用该 object 调用所需的 method.So 您的 doPost 方法如下所示:

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    response.setContentType("text/html/charset-UTF-8");
    out =response.getWriter();
    Login l1 =new Login();//creating object of class
    boolean login = l1.processLogin(username,password); //using object to call the method
   //do further process

此外,使用 PreparedStatement 到数据库中的 select 值并避免任何 SQL injection 。因此您的方法代码如下所示:

PreparedStatement ps = MyCon.prepareStatement("select *from input_form where username=? AND password= ?");
    //setting value for "?"
    ps.setString(1, username);
    ps.setString(2, password);
    ResultSet rs = ps.executeQuery();
    //if true
    if (rs.next()) {
    result=true;
    }else{
     result = false;
    }