java.lang.IllegalArgumentException 尝试执行 JSTL < c:if > 条件时

java.lang.IllegalArgumentException when trying to execute JSTL < c:if > condition

如果给定类别中的产品少于 5 种,我试图告诉我的程序在每个产品上打印一条消息。但是当我在浏览器中测试条件时,当我点击一个类别时(即使该类别有超过 5 个产品),页面变为空白并且日志标记以下错误:

java.lang.IllegalArgumentException: Cannot convert {[entity.Product[ id=36 ], entity.Product[ id=37 ], entity.Product[ id=38 ], entity.Product[ id=39 ], entity.Product[ id=160 ]]} of type class org.eclipse.persistence.indirection.IndirectList to class java.lang.Long

我认为我的 c:if 情况有问题。

    <c:set var="product" value="${categoryProducts}"/>

<c:if test="${categoryProducts > 5}">
                         <div id="pd_msg">SALE!</div>
                          </c:if>

试试这个:

    <c:set var="product" value="${categoryProducts}"/>

    <c:if test="${categoryProducts.size() > 5}">
        <div id="pd_msg">SALE!</div>
    </c:if>

异常告诉您您正在尝试比较 List(左侧)和 Long(右侧)。 但是你只能比较相同类型的对象,这就是为什么你需要先调用 size(),这会给你 列表中的项目总数。

@BadK 建议的解决方案很好,但如果它对你不起作用,就像它对我不起作用,下面的代码对我有用:

 <c:if test="${fn:length(categoryProducts) < 5}">
        <div id="pd_msg">SALE!</div>
    </c:if>

在此处找到此解决方案:Evaluate if list is empty JSTL