我正在尝试将列表作为参数发送到我想要显示的 JSP 文件。 我的 JSP 文件名为 showList.jsp。
创建了一个 servlet,我用它来控制程序中的所有内容。当用户单击“显示列表”按钮时,将执行一些代码,该代码将打印出列表:
我的代码:
if (session.getAttribute("show") == "show") {
List opr = null;
try {
opr = func.showlist(opr);
for(int i = 0; i < opr.size(); i++){
System.out.println(opr.get(i));
}
} catch (Exception e) {
System.out.print("Error found, when trying to show list");
}
session.removeAttribute("administrator");
session.removeAttribute("show");
session.removeAttribute("create");
return;
}
在这里您可以看到它只打印我的数组列表中的内容(大小)。
更新的代码:
List opr = null;
try {
opr = func.showlist(opr);
for(int i = 0; i < opr.size(); i++){
System.out.println(opr.get(i));
}
request.setAttribute("list", opr);
} catch (Exception e) {
System.out.print("Error found, when trying to show list");
}
session.removeAttribute("administrator");
session.removeAttribute("show");
getServletConfig().getServletContext().getRequestDispatcher("/getList.jsp");
}
最佳答案
尝试使用JSP JSTL来迭代JSP中的列表
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
...
<c:if test="${not empty list}">
<table>
<c:forEach var="x" varStatus="status" items="${list}">
<tr>
<td><c:out value="${x}" /></td>
</tr>
</c:forEach>
</table>
</c:if>
只需使用 ServletRequest#setAttribute() 将数据设置为请求属性.
有关更多示例,请查看以下帖子:
关于java - 将列表对象作为参数发送到jsp端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23501836/