Cannot cast from Object to int JSP

Asked

Viewed 134 times

1

I am developing an application using JSP and servelt in which I want to get the total amount of records from my tb_driver table,created a servelt in which I passed the method that makes the query and created a session but when taking the session created in servelet and put in the page listMotorista2 it appears the following error.An error occurred at line: 47 in the jsp file: /listaMotoristas2.jsp Cannot cast from Object to int

 public int totalRegistros(){

     try {
        con = Conecta.conexao();
    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Conecta.class.getName()).log(Level.SEVERE, null, ex);
    }


            try {

       String sql="Select count(*) as contaRegistros from tb_motorista";
        Statement statement = con.createStatement();     

       ResultSet rs = statement.executeQuery(sql);    
        rs.next();
        int totalRegistros=Integer.parseInt(rs.getString("contaRegistros"));
        return totalRegistros;

    } catch (Exception e) {
        JOptionPane.showConfirmDialog(null,e);

}
            return 0;
}

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

     MotoristasDAO dao= new MotoristasDAO();

     try {

          int totalMotorista=dao.totalRegistros();

     request.setAttribute("totalMotoristas", totalMotorista);

     RequestDispatcher rd= 
   request.getRequestDispatcher("/listaMotoristas2.jsp");
    rd.forward(request, response);

    } catch (Exception e) {
    }

   }

            <%

    int totalRegistros= (int) request.getAttribute("totalMotorista");//Cannot cast from Object to int


          %> 
  • If you insert a System.out.println(rs.getString("contaRegistros"));, what is the result? This output could be right after the rs.next();

  • Weslley Tavares returns the number of records 5

1 answer

2


request.setAttribute("totalMotoristas", totalMotorista);

The Httpservletrequest.setAttribute() parameters are String and Object. totalMotorista is int, which is not Object but a primitive type.

Switch to Integer in points:

- public Integer totalRegistros(){
- Integer totalRegistros=Integer.parseInt(rs.getString("contaRegistros"));
- Integer totalMotorista=dao.totalRegistros();
  • 1

    worked here thanks

  • So take a vote ;-)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.