Home > Net >  Type mismatch: cannot convert from Object to List<User>
Type mismatch: cannot convert from Object to List<User>

Time:10-03

HomeController.java

package com.project.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.project.entity.User;
import com.project.model.ListUsers;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

@WebServlet("/home")
public class HomeController extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    @Resource(name="jdbc/MyDB")
    private DataSource dataa;
    
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        String page = request.getParameter("page");
        page.toLowerCase();
        switch (page) {
        case "home": {
            List<User> listUserss = new ArrayList<>() ;
            listUserss= new ListUsers().listUsers(dataa);
            request.setAttribute("listUserss", listUserss);
            request.getRequestDispatcher("index.jsp").forward(request, response);
            
        }
        case "listUsers":{
            request.getRequestDispatcher("listUsers.jsp").forward(request, response);
        }
        default: 
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }
    }

}

ListUsers.java

package com.project.model;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import com.project.entity.User;

public class ListUsers {
    public List<User> listUsers(DataSource dataa){
        
    List<User> listUsers = new ArrayList<>();
    
    //==== build SQL database ====
    ResultSet re = null;
    Connection connect = null;
    java.sql.Statement st= null;
    
    
    try {
        // =====is used to establish a connection with the database.
        connect =dataa.getConnection();
        
        // Create a SQL statement string
        String query = "Select * FROM newpro.users;";
        st = connect.createStatement();
        
        // Execute SQL query
        re = st.executeQuery(query);
        
        // print the result 
        while(re.next()) {
            listUsers.add( new User(re.getString("email"),re.getString("username"),re.getInt("users_id")));
        }
        
    } catch (SQLException e) {
        
        e.printStackTrace();
    }
    
    
    return listUsers;
    

    }
}


User.java

package com.project.entity;

public class User {
    private String email;
    private String username;
    private int users_id;
    
    public User(String email,String username,int users_id) {
        this.email = email;
        this.username =username;
        this.users_id= users_id;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public int getUsers_id() {
        return users_id;
    }
    public void setUsers_id(int users_id) {
        this.users_id = users_id;
    }
    
    
    

}

listUsers.jsp

<%@page import="java.util.ArrayList"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ page import="java.util.List" %>
    <%@ page import="com.project.entity.User" %>
    
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>List of Users</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet"  >

</head>
<body>
<header >
    <div >
      <div >
        <a href="<%=request.getContextPath()%>/home?page=home" >
          <svg  width="40" height="32" role="img" aria-label="Bootstrap"></svg>
        </a>

        <ul >
          <li ><a href="<%=request.getContextPath()%>/home?page=home " >Home</a></li>
           <li ><a href="<%=request.getContextPath()%>/home?page=listUsers" >About</a></li>
        </ul>

        <form >
          <input type="search"  placeholder="Search..." aria-label="Search">
        </form>

        <div >
          <button type="button" >Login</button>
          <button type="button" >Sign-up</button>
        </div>
      </div>
    </div>
  </header>
    
    
    
    <h1>List of Users</h1>
    <hr/>
    <table border="1">
            <thead>
                <th>username</th>
                <th>email</th>
                <th>user_id</th>
            </thead>
            <%
            /*################################## This is the Error >>>>>>>>>  ###################*/
                List<User> listu = request.getAttribute("listUserss");
            
            %>
    </table>
    
    
        
    
    
    
    
    <footer >
    <p >© 2022 Company, Inc</p>

    <a href="/" >
      <svg  width="40" height="32"><use xlink:href="#bootstrap"></use></svg>
    </a>

    <ul >
      <li ><a href="<%=request.getContextPath()%>/home?page=home " >Home</a></li>
      <li ><a href="<%=request.getContextPath()%>/home?page=listUsers" >About</a></li>
    </ul>
  </footer>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-u1OknCvxWvY5kfmNBILK2hRnQC3Pr17a RTT6rIHI7NnikvbZlHgTPOOmMi466C8" crossorigin="anonymous"></script>

</body>
</html>

the error in listUsers.jsp says: Type mismatch: cannot convert from Object to List<User>

CodePudding user response:

Please cast Object to List<User>. Request's getAttribute method returns the object and it will not know in which class to convert. So you have to explicitly cast the object. Make sure request.getAttribute("listUserss") is not null else it will throw NullPointerException.

<%
   List<User> listu = (List<User>) request.getAttribute("listUserss");
%>
  • Related