如何解决此错误?我将thymelaf与spring一起使用,在解析以下html段时出现错误。
org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'items' cannot be found on null
当我向购物车添加一些东西时,它就起作用了。问题是当它是空的。
`
<tr th:each="item : ${session.shoppingCart.items}">
<td th:text="${item.book.id}"></td>
<td th:text="${item.book.title}"></td>
<td><span th:text="${item.book.price}"></span>cash</td>
<td>
<form action="#" th:action="@{/cart/update}" method="post">
<input type="hidden" th:value="${item.book.id}" name="id"/>
<input type="number" min="1" th:value="${item.quantity}" name="qty"/>
<button type="submit">UPDATE</button>
</form>
</td>
<td><span th:text="${item.subTotal}"></span>cash</td>
<td>
<form action="#" th:action="@{/cart/remove}" method="post">
<input type="hidden" th:value="${item.book.id}" name="id"/>
<button type="submit">remove</button>
</form>
</td>
</tr>
`
在你的评论中,你说如果你向购物车添加了一些东西,它就会工作,这意味着shoppingCart存在于会话范围中,但shoppingCart中没有任何项目。
您所需要做的就是首先检查项目是否存在。(如果它不存在,你不必显示它!(
<div th:if="${!session.shoppingCart.items}">
your code
</div>
您也可以为此使用th:unless
,并将代码放在具有以下属性的div下:
<div class="itemslist" th:unless="${#lists.isEmpty(session.shoppingCart.items)}">
<tr th:each="item : ${session.shoppingCart.items}">
<td th:text="${item.book.id}"></td>
<td th:text="${item.book.title}"></td>
<td><span th:text="${item.book.price}"></span>cash</td>
<td>
<form action="#" th:action="@{/cart/update}" method="post">
<input type="hidden" th:value="${item.book.id}" name="id"/>
<input type="number" min="1" th:value="${item.quantity}" name="qty"/>
<button type="submit">UPDATE</button>
</form>
</td>
<td><span th:text="${item.subTotal}"></span>cash</td>
<td>
<form action="#" th:action="@{/cart/remove}" method="post">
<input type="hidden" th:value="${item.book.id}" name="id"/>
<button type="submit">remove</button>
</form>
</td>
</tr>
</div>
检查此参考
现在出现了这样一个错误。
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "!session.shoppingCart.items"
org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'items' cannot be found on null
<div th:if="${!session.shoppingCart.items}">
<tr th:each="item : ${session.shoppingCart.items}">
<td th:text="${item.book.id}"></td>
<td th:text="${item.book.title}"></td>
<td><span th:text="${item.book.price}"></span>cash</td>
<td>
<form action="#" th:action="@{/cart/update}" method="post">
<input type="hidden" th:value="${item.book.id}" name="id"/>
<input type="number" min="1" th:value="${item.quantity}" name="qty"/>
<button type="submit">UPDATE</button>
</form>
</td>
<td><span th:text="${item.subTotal}"></span>cash</td>
<td>
<form action="#" th:action="@{/cart/remove}" method="post">
<input type="hidden" th:value="${item.book.id}" name="id"/>
<button type="submit">remove</button>
</form>
</td>
</tr>
</div>