JSP foreach不打印列表的内容

时间:2012-04-27 22:31:07

标签: jsp jstl

我在jsp中遇到一个小问题

我尝试在jstl/jsp - iterating over a vector of beans中做所有事情,但我无法在屏幕上打印任何内容

这里有一些代码:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Shop products</h1>
        <table>
            <c:forEach var="item" items="${products}">
                <tr>
                    <td>
                        <c:out value="${item.name}"/>
                    </td>
                <td>
                    <c:out value="${item.amount}"/>
                </td>
                </tr>
            </c:forEach>
        </table>
    </body>
</html>

我的servlet processRequest():

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    products = new LinkedList<ProductHandler>();
    products.add(new ProductHandler("A", 5));
    products.add(new ProductHandler("B", 10));
    products.add(new ProductHandler("C", 7));
    request.setAttribute("products", products);
    getServletContext().getRequestDispatcher("/JSP/shop.jsp").forward(request, response);
}

和ProductHandler:

public class ProductHandler {
    private String name;
    private int amount;

    public ProductHandler() { 
        name = null;
        amount = 0;
    }

    public ProductHandler(String name, int amount) {
        this.name = name;
        this.amount = amount;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the amount
     */
    public int getAmount() {
        return amount;
    }

    /**
     * @param amount the amount to set
     */
    public void setAmount(int amount) {
        this.amount = amount;
    }

}

我非常感谢指出我犯的任何错误

1 个答案:

答案 0 :(得分:4)

尝试将此行添加到shop.jsp

的顶部
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>