代码之家  ›  专栏  ›  技术社区  ›  Gastón Saillén Michael Lehenbauer

未显示mysql-servlets和jsp值的表

  •  -1
  • Gastón Saillén Michael Lehenbauer  · 技术社区  · 7 年前

    我是个新手,每天都在学习关于JSP、servlets等的新东西,我设置了所有的东西,将数据库中的所有用户显示到浏览器中的一个表中,然后只需要一个按钮就可以更改其中的1个值,所以我成功地做到了这一点。

    我的 AdminPanel.jsp (在这里,我设置了表以显示数据库中的所有条目)

      <form action="AdminPanel" method="get">
    
      <table style="width:100%">
          <caption>Usuarios Registrados</caption>
    
          <tr>
        <th>Nombre</th>
        <th>Apellido</th>
        <th>Usuario</th>
        <th>Estado</th>
        <th>Habilitar</th>
      </tr>
    
       <tr>
    
        <c:forEach var="row" items="${memberList}">
    
        <tr>
            <td><c:out value="${row.firstname}"/> </td>
            <td><c:out value="${row.lastname}"></c:out> </td>
            <td><c:out value="${row.username}"></c:out> </td>
            <td><c:out value="${row.type}"></c:out> </td>
            <td><a href="AdminPanel.jsp" name="Edit">Habilitar usuario</a> </td>
        </tr>
    </c:forEach>
      </tr>
    
    </table>
            </form> 
    

    现在,我有一个 userDAO 它连接到数据库并设置用户bean的值(我的pojo类,具有firstname、lastname等的所有setter和getter)

    用户道.java

      public static UserBean adminPanel(UserBean bean) {
    
             //preparing some objects for connection 
             Statement stmt = null;    
    
             String firstname = bean.getFirstName();
             String lastname = bean.getLastName();
             String username = bean.getUsername();
             int tipo = bean.getType();
    
                String searchQuery =
                   "select firstname,lastname,username,tipo from idusuario";
    
          // Tracing the process
          System.out.println("Nombre:  " + firstname);          
          System.out.println("Apellido: " + lastname);  
          System.out.println("Usuario: "+username);
          System.out.println("Estado Usuario :" + tipo);  
          System.out.println("Query Panel Admin :" + searchQuery);  
    
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException ex) {
                System.out.println("Error al cargar el driver");
                System.out.println(ex.getMessage());
            }
    
          try 
          {
             //connect to DB 
             currentCon = DriverManager.getConnection("jdbc:mysql://localhost:3306/usuarios", "root", "admin");
             stmt=currentCon.createStatement();
             rs = stmt.executeQuery(searchQuery);   
             boolean more = rs.next();
    
             // if user does not exist set the isValid variable to false
             if (!more) 
             {
                System.out.println("Para poder utilizar el sistema debe registrarse");
                bean.setValid(false);
             } 
    
          } 
    
          catch (Exception ex) 
          {
             System.out.println("Error logueandose, posible problema de conexion de base de datos " + ex);
          } 
       } 
    
    } 
    

    还有我的 AdminPanel.java 伺服电动机

     @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
    
    
             ArrayList<UserBean> member= new ArrayList<UserBean>();
            try {
                while(rs.next()) {
                    UserBean user = new UserBean();
                    user = UserDAO.adminPanel(user);
                    user.setFirstName(rs.getString("firstname"));
                    user.setLastName(rs.getString("lastname"));
                    user.setUserName(rs.getString("username"));
                    user.setType(rs.getInt("type"));
                    member.add(user);
                    request.setAttribute("memberList", member);
                }       } catch (SQLException ex) {
                Logger.getLogger(AdminPanel.class.getName()).log(Level.SEVERE, null, ex);
            }
    
    
        }
    

    我要在数据库中检索的结果(使用查询 SELECT firstname,lastname,username,tipo,admin from idusuario )

    enter image description here

    现在,在我的输出中,它没有显示任何内容,查询是正确的,我已经用mysqlWorkbench签出了它,它显示了我想要的结果,我检索了数据并存储了它,但我不知道为什么现在没有显示任何内容。

    这是我的输出

    enter image description here

    在我的导入中,我的rs也从userdao中提取出来。

    import static com.login.UserDAO.rs;  (resultSet)
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Jonathan Laliberte    7 年前

    将数据库逻辑与servlet分离是很重要的,它使管理更加容易。为数据库连接创建单独的类也很有用。之所以没有得到任何结果,是因为在UserDAO类中,没有从结果集中获得任何结果。

    为数据库连接创建一个类。我们可以随时调用这个数据库。

    public class DBConnection {
        private static String url = null;
        private static Connection conn = null;
         public static Connection getConnection(){
         try{
    
           Class.forName("com.mysql.jdbc.Driver");
           url = "jdbc:mysql://localhost:3306/usuarios";
    
         conn = DriverManager.getConnection(url,"root","admin");
         }   catch (Exception e) {
                System.out.println(e);
            } 
         return conn;
         }
    }
    

    以及我们的userdao类的adminpanel方法:

        //Now we can use this like this, i looked at your code and saw you wanted to have a list of UserBean objects.. we can do that like this:
    public List<UserBean> adminPanel(){
        ArrayList<UserBean> users = new ArrayList<UserBean>();
        //get connection from our DBConneciton class we created earlier
        try(Connection conn= DBConnection.getConnection()){
        //create our sql statement
       PreparedStatement pst = conn.prepareStatement("select firstname,lastname,username,tipo from idusuario;"); 
             //execute query
             pst.executeQuery();   
           //now get results
        ResultSet rs = pst.executeQuery();
          //while ResultSet has results
         while (rs.next()) {
        //create new user object to hold the info in
        UserBean user = new UserBean();
        //get the results from resultset     
        String firstname = rs.getString(1);
        String lastname = rs.getString(2);
        String username = rs.getString(3);
        int type = rs.getInt(4);
        //set results to user object
        user.setFirstName(firstname);
        user.setLastName(lastname);
        user.setUserName(username);
        user.setType(type);
    
        users.add(user); //add userobject to list of userobjects
    
          }
    
            } catch (SQLException e) {
                e.printStackTrace();
            }
         //we don't need to close our db connection because the try statement does it for us   
    return users; //return list of users
    }   
    

    现在要访问这些,我们在servlet中需要做的就是:

    @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
              UserDAO u = new UserDAO(); //instantiate class
    
           //get our list of users
         List<UserBean> users = u.adminPanel();
           //set our list to request
         request.setAttribute("memberList", users);
    
         //forward to jsp page
            RequestDispatcher rs = request.getRequestDispatcher("AdminPanel.jsp");
                rs.forward(request, response);
    
    
        }
    

    你的JSP上的一切看起来都很好,所以应该可以工作,如果你有任何问题或问题,请告诉我。

    编辑: 一些调试思路:

    在servlet中,这样做可以查看用户列表有多大:

    ...
    //get our list of users
    List<UserBean> users = u.adminPanel();
     //check if we are actually getting something from the database
     System.out.println(users.size());
    

    如果大小为0,则表示我们的查询有问题。如果使用以下查询手动查询数据库,请检查是否从数据库中获取任何信息:

    select firstname,lastname,username,tipo from idusuario;
    

    编辑2

    尝试删除 <c:out tags:

      <c:forEach var="row" items="${memberList}">
        <tr>
            <td>${row.firstname}</td>
            <td>${row.lastname}</td>
            <td>${row.username}</td>
            <td>${row.type}</td>
            <td><a href="AdminPanel.jsp" name="Edit">Habilitar usuario</a> </td>
        </tr>
    </c:forEach>