简体   繁体   English

单击按钮将ArrayList发送到另一个页面

[英]send ArrayList to another page when a button is clicked

I want to send an ArrayList to another page after a button is clicked. 我想在单击按钮后将ArrayList发送到另一个页面。

function gotosave(){
<% 
request.setAttribute("list", ar);
request.getRequestDispatcher("savecard.jsp").forward(request,response);
%>
}

<button type="submit" name="save" style="float:right;" class="btn btn-info" 
 onclick="gotosave()">SAVE</button> 

"ar" is my array list. “ ar”是我的数组列表。

This is my First Question here so if i have missed the correct format then don't mind. 这是我的第一个问题,因此,如果我错过了正确的格式,请不要介意。

You're trying to mix Java and JavaScript here. 您正在尝试在此处混合使用Java和JavaScript。 It won't work. 它不会工作。 In JSP (or any similar backend rendering technology) first Java code will be executed, then the page will be rendered by your browser, and only then JavaScript code will execute. 在JSP(或任何类似的后端呈现技术)中,首先将执行Java代码,然后由浏览器呈现页面,然后才执行JavaScript代码。

What happens now: First this code is executed: 现在会发生什么:首先执行此代码:

<% 
request.setAttribute("list", ar);
request.getRequestDispatcher("savecard.jsp").forward(request,response);
%>

Then JavaScript function is generated, and it looks like this: 然后,将生成JavaScript函数,如下所示:

function gotosave(){
}

And if you haven't been forwarded yet, when you click the button, nothing will happen. 如果尚未转发,则单击该按钮时将不会发生任何事情。

Another problem with your code is that you're forwarding to JSP, and not to your servlet. 代码的另一个问题是您要转发到JSP,而不是servlet。 Especially if you want to pass some parameters, that shouldn't be the case. 尤其是如果您要传递一些参数,情况并非如此。

What I would suggest in your case: Remove JS function, and wrap everything in a form. 在您的情况下,我的建议是:删除JS函数,并将所有内容包装成表格。 Then specify action of this form, and point it to your servlet (or JSP, if you insist) 然后指定这种形式的操作,并将其指向您的servlet(或JSP,如果您坚持要求的话)

<form method = "POST" action = "./savecard.jsp"> 
   <input type = 'hidden' name = 'list' value = '${ar}' /> 
   <button type="submit" name="save" style="float:right;" class="btn btn-info">SAVE</button>  
</form>

OK you can achieve this objective using two ways . 好的,您可以使用两种方法实现此目标。 Ones is using a hidden field. 有人正在使用隐藏字段。 That is the traditional and efficient way of doing it. 这是传统的高效方法。

<input type="hidden" name="userId" value="<your array list>"> 

Another option is to use a session variable. 另一种选择是使用会话变量。 Using a session storage , you can access your arraylist on any jsp within the project as long as you dont clear the session. 使用会话存储,只要不清除会话,就可以访问项目中任何jsp上的arraylist。

Set your attribute in the current jsp like this 像这样在当前的jsp中设置属性

session.setAttribute("arraylist", <your arraylist variable>);

In your other JSP use this 在您的其他JSP中使用此

int arraylist = session.getAttribute("arraylist");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM