java - 循环对象数组并在 JSP 中使用 c:if jstl
问题描述
我目前正在开发一个小型 Web 应用程序项目。主页有一个链接,一旦单击,就会调用一个 servlet,该 servlet 从数据库中检索数据(以对象数组列表的形式),将数组列表添加到会话(作为客户),并重定向到对象(客户)所在的 jsp显示在表格中。有一个“更多详细信息”列,其中每一行都有一个按钮,该按钮将表单提交给另一个 jsp,其中包含一个隐藏的输入值,其中 customerNumber 作为其值,num 作为其名称。
我希望在第二个 jsp 中遍历所有客户并仅显示其 customerNumber 与从第一个 jsp 发送的客户相匹配的客户。
当前代码:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<% String hidden = request.getParameter("num"); %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Customer Details Page</title>
</head>
<body>
<div>
<c:forEach var="c" items="${customers}">
<c:if test = "${hidden == c.customerNumber}">
<table>
<thead>
<tr>
<th>Customer Phone</th><th>Customer Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>${c.phone}</td><td>${c.country}</td>
</tr>
</tbody>
</table>
</c:if>
</c:forEach>
</div>
</body>
</html>
上面的代码只打印表格标题。任何帮助表示赞赏。
解决方案
发现问题,试图直接从 jstl 标签访问来自 scriplet 的变量。以下代码工作正常:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String hidden = request.getParameter("num");
pageContext.setAttribute("reqNum",hidden);
%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Customer Details Page</title>
</head>
<body>
<div>
<c:forEach var="c" items="${customers}">
<c:if test = "${reqNum == c.customerNumber}">
<table border="1">
<thead>
<tr>
<th>Customer Phone</th><th>Customer Country</th>
</tr>
</thead>
<tbody>
<tr>
<td><c:out value="${c.phone}" /></td><td><c:out value="${c.country}" /></td>
</tr>
</tbody>
</table>
</c:if>
</c:forEach>
</div>
</body>
</html>