【问题标题】:How to connect my servlet to the boolean method from another class?如何将我的 servlet 连接到另一个类的布尔方法?
【发布时间】:2020-09-02 08:36:20
【问题描述】:

我已经尝试了一些变体,我当然导入了包含我在我的 Servlet 中使用的布尔方法的类,但它仍然看不到该方法。

这是我的类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?

【问题讨论】:

    标签: servlets methods boolean


    【解决方案1】:

    创建您需要调用的类的object,然后使用该object 调用所需的方法。所以您的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 来选择数据库中的值并避免使用任何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;
        }
    

    【讨论】:

      猜你喜欢
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      • 2012-07-07
      • 2020-07-02
      相关资源
      最近更新 更多