首页 > 解决方案 > 循环遍历 ArrayList 并更新属性

问题描述

我正在尝试遍历 ArrayListstart.jsp并将每个项目传递到不同的 jsp 中,destination.jsp. 我目前正在使用会话,并且我知道该session.setAttribute函数将覆盖该属性的先前值。这是我的代码:

开始.jsp:

// Main AL has the type ArrayList<ArrayList<String>>. I am trying to loop through the mainAL and pass each item in it to destination.jsp. 

...
// This snipet of code creates a button for each element in mainAL and submits the element to destination.jsp when clicked.
for (ArrayList<String> al : mainAL)
{
    <form action="destination.jsp" method="get">
        <input type="submit"/>
    </form>
    <% session.setAttribute("list", al); %>
}
...

目的地.jsp:

...
<% ArrayList<String> result = (ArrayList<String>) session.getAttribute("list"); %>
<%out.println(list);%>
...

如果mainAL有超过 1 个项目,destination.jsp则从 for 循环生成的每个实例将仅显示来自 的最后一个 ArrayList mainAL。我应该如何解决这个问题?有没有办法将每个 ArrayList 传递给destination.jsp它的值而不被覆盖?

标签: javajspsessionarraylist

解决方案


session.setAttribute() 函数全局设置一个值。这意味着,您覆盖每个循环周期中的值。您将不得不进行隐藏输入,以便您放置数据,以便将其作为请求 url 中的 GET 参数传递到您的其他目标站点。在目标站点,您必须从请求 url 中检索该数据。当你想保持你的 url 干净时,你也可以使用 POST。我还建议使用会话令牌执行此类操作,而不是通过输入传递列表。

我希望这对你有帮助:)


推荐阅读