如何用Jstl c:forEach显示随机数据?
How to display random data with Jstl c:forEach?
我试图在用户访问他之前选择的产品页面时向他显示 2 个随机产品。有点像意见箱。
为此,我使用 <c:forEach var="product" items="${categoryProducts}" begin="0" end="1" step="1" varStatus="iter">
它在显示前两个产品时效果很好,但它非常有限,因为它总是显示相同的两个产品(第一个和第二个)。
我怎样才能提升标签并使其更智能?我希望程序每次都显示 2 种不同的产品...像 first-second
third-fourth
等等...
How can I give the tag a boost and make it smarter?
您犯了概念性错误。 JSTL是为了表示,不是为了逻辑。 Tags/EL 基本上应该保持"dumb" 并且只呈现已经准备好的模型。负责实际逻辑的是模型准备 Java 代码,通常(直接)由 servlet 执行。
您应该关注负责准备 ${categoryProducts}
变量的 Java 代码。这正是必须更改为 "make it smarter" 的代码。正是您必须在代码中添加 "smartness" 。没有魔法,只有逻辑。
最简单的方法是在将 ${categoryProducts}
放入请求范围之前使用 Collections#shuffle()
。例如:
List<CategoryProduct> categoryProducts = categoryProductService.list();
Collections.shuffle(categoryProducts);
request.setAttribute("categoryProducts", categoryProducts);
我试图在用户访问他之前选择的产品页面时向他显示 2 个随机产品。有点像意见箱。
为此,我使用 <c:forEach var="product" items="${categoryProducts}" begin="0" end="1" step="1" varStatus="iter">
它在显示前两个产品时效果很好,但它非常有限,因为它总是显示相同的两个产品(第一个和第二个)。
我怎样才能提升标签并使其更智能?我希望程序每次都显示 2 种不同的产品...像 first-second
third-fourth
等等...
How can I give the tag a boost and make it smarter?
您犯了概念性错误。 JSTL是为了表示,不是为了逻辑。 Tags/EL 基本上应该保持"dumb" 并且只呈现已经准备好的模型。负责实际逻辑的是模型准备 Java 代码,通常(直接)由 servlet 执行。
您应该关注负责准备 ${categoryProducts}
变量的 Java 代码。这正是必须更改为 "make it smarter" 的代码。正是您必须在代码中添加 "smartness" 。没有魔法,只有逻辑。
最简单的方法是在将 ${categoryProducts}
放入请求范围之前使用 Collections#shuffle()
。例如:
List<CategoryProduct> categoryProducts = categoryProductService.list();
Collections.shuffle(categoryProducts);
request.setAttribute("categoryProducts", categoryProducts);