Noroc Sergey
Noroc Sergey

Reputation: 197

How to show a list in JSP?

This Servlet, I do GROUP BY on color car. Inserted into the request and advertise in jsp but it does not convert.

    Query query = session.createQuery("select count(carColor), carColor from Cars group by carColor order by carColor");
    List<Cars> list = query.list();
    Iterator iter = list.iterator();
    while (iter.hasNext()) {
        Object[] obj = (Object[]) iter.next();
        System.out.println(obj[0] + "  " + obj[1]);

    }

    request.setAttribute("list", list); 

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

Console: 2 White 10 Black 5 Blue

JSP: [[Ljava.lang.Object;@1f3b536, [Ljava.lang.Object;@fdffb1,]]

Upvotes: 1

Views: 2431

Answers (1)

JB Nizet
JB Nizet

Reputation: 692181

Your code really makes no sense:

List<Cars> list = query.list();

In the above line, you declare that your list is a list of Cars (which it is not)

Iterator iter = list.iterator();
while (iter.hasNext()) {
    Object[] obj = (Object[]) iter.next();

Then you iterate on the list, and cast each element to Object[]. How could a Cars instance ever be an Object[]? The list should be declared as List<Object[]>, and you shouldn't use raw types. Your loop should be written as

Iterator<Object[]> iter = list.iterator();
while (iter.hasNext()) {
    Object[] obj = iter.next();

Or, even simpler:

for (Object[] obj : list) {

Now, in the JSP, I suspect you're just using ${list} to display the list. This simply calls the toString() method on the list, which itself calls the toString() method of each element. Since each element is an Object[], the result string is [Ljava.lang.Object;@1f3b536, which means "array of Object with hashCode 1f3b536".

To display the elements of the list, you should iterate over the list, as you must do it in the Java code:

<c:forEach var="array" items="${list}">
    Count: ${array[0]} - Color: <c:out value="${array[1]}"/> <br/>
</c:forEach>

Upvotes: 5

Related Questions