简体   繁体   中英

Send ArrayList<Product> from Servlet and receive in JSP

This is my servlet code. Here, products is an object of ArrayList<Products> and I am sending this to a JSP file. request is an object of type HttpServletRequest .

request.setAttribute("listOfProducts", products);
request.getRequestDispatcher("UpdateProduct.jsp").forward(request, response);

In my JSP, I tried to receive this.

ArrayList<Products> product = request.getAttribute("listOfProducts");

It shows me this error

Type mismatch: cannot convert from Object to ArrayList

Then I tried this

ArrayList<Products> product = (ArrayList<Products>) request.getAttribute("listOfProducts");

Then I got this warning

Multiple annotations found at this line: - Type safety: Unchecked cast from Object to ArrayList - Type mismatch: cannot convert from Object to ArrayList

The following is the modern (environmentally friendly!) way to do this:

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:jsp="http://java.sun.com/JSP/Page"
      xmlns:c="http://java.sun.com/jsp/jstl/core">
<head>
    ...
</head>
<body>
    ...
    <c:forEach items="${listOfProducts}" var="product">
        <tr><td>${product.id} </td>
            <td>${product.name} </td>
            <td>${product.whatever} </td></tr>
    </c:forEach>
    ...
</body>
</html>

The file extension of your JSP must be .jspx .

No java code is required in the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM