c:foreach没有打印物体

时间:2016-12-05 20:39:32

标签: java html jsp servlets

我对JSP非常陌生。无论如何,我试图使用c:foreach打印列表中的每个对象,但它不起作用,我无法弄清楚原因。我已经检查过类似的问题,但没有解决我的问题。

 [HttpPost("RentCommunityAmenity")]
 public JsonResult Post([FromBody]MyModel value)
 {
 }
 public class MyModel
 {
        public int idCommunityAmenity { get; set; }
        public int idHome { get; set; }
        public DateTime startDate { get; set; }
        public DateTime endDate { get; set; }

 }

底部代码有效--- accounts.get(0)等。但是我无法使用它,因为如果我向数据库添加数据,那么每次都要添加更多代码。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您没有提供有关您的BankAccount类的信息,因此我会做出一个假设:

package testingThings.EL.linkedlist;

public class BankAccount {
    protected String accountName;
    protected double accountBalance;

    public BankAccount(String accountName, double accountBalance) {
        this.accountName = accountName;
        this.accountBalance = accountBalance;
    }

    public String getAccountName() {
        return accountName;
    }

    public void setAccountName(String accountName) {
        this.accountName = accountName;
    }

    public double getAccountBalance() {
        return accountBalance;
    }

    public void setAccountBalance(double accountBalance) {
        this.accountBalance = accountBalance;
    }

}

我更改了 A ccountBalance a ccountBalance以遵守惯例。

在你的JSP中,你需要LeHill提到的那一行。

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

不要忘记协议:http://

JSP:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="testingThings.EL.linkedlist.BankAccount"%>
<%@ page import="java.util.LinkedList"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <%
        LinkedList<BankAccount> accounts = new LinkedList<BankAccount>();
        accounts.add(new BankAccount("acc1", 1000.00));
        accounts.add(new BankAccount("acc2", 2000.00));

        pageContext.setAttribute("accounts", accounts);
    %>
    <c:forEach items="${accounts}" var="acct">
        <p>${acct.accountName}</p>
        <br />
        <p>${acct.accountBalance}</p>
        <br />
    </c:forEach>
</body>
</html>

浏览器中的输出:

acc1

1000.0

acc2

2000.0

答案 1 :(得分:0)

看起来你没有吸气剂和二传手。 您的scriptlet的属性名称为&#34; accountName&#34;。 JSTL希望&#34; get&#34;或&#34;是&#34;作为bean方法名称的开头。 你不能直接调用该属性。你必须使用getter方法。 如果您创建了一个名为&#34; getAccountName&#34;它应该工作。

相关问题