Java Servlet 将数组列表作为请求属性发送到 JSP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22419386/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 15:37:15  来源:igfitidea点击:

Servlet send arraylist to JSP as request attribute

javajspservlets

提问by Nathaniel Wendt

I am attempting to send an ArrayList from a servlet to a JSP page. In the Servlet:

我正在尝试将 ArrayList 从 servlet 发送到 JSP 页面。在 Servlet 中:

List<ItemObj> myList = new ArrayList<ItemObj>();   
req.setAttribute("list", myList);
req.getRequestDispatcher("page.jsp").forward(req,resp);

In the JSP:

在 JSP 中:

<% List<ItemObj> myList = (ArrayList<ItemObj>) request.getParameter("list"); %>

However, I keep getting an error: Cannot cast from String to List. I have found sources that indicate that I can cast as such:

但是,我不断收到错误消息:无法从字符串转换为列表。我找到了表明我可以这样投射的来源:

how to send ArrayList from jsp to servlet

如何将ArrayList从jsp发送到servlet

Send array of objects from servlet to JSP

将对象数组从 servlet 发送到 JSP

What am I doing wrong? Thank you!

我究竟做错了什么?谢谢!

采纳答案by Keerthivasan

You are setting listas request attribute and getting it back as request parameter

您正在设置list为请求属性并将其作为请求参数取回

Use <% List<ItemObj> myList = (ArrayList<ItemObj>) request.getAttribute("list"); %>

<% List<ItemObj> myList = (ArrayList<ItemObj>) request.getAttribute("list"); %>

回答by Santino 'Sonny' Corleone

Instead of request.getParameteruse

而不是request.getParameter使用

<% List<ItemObj> myList = (ArrayList<ItemObj>) request.getAttribute("list"); %>

<% List<ItemObj> myList = (ArrayList<ItemObj>) request.getAttribute("list"); %>

request.getParameteris used to retrieve form parameters.

request.getParameter用于检索表单参数。

回答by Kode Charlie

Sotirious is spot-on. You need to call getAttribute.

Sotiirious 恰到好处。您需要调用 getAttribute。

But beyond that, you should be privy to the scope of your attribute: is it scoped to (i) page, (ii) request, (iii) session, or (iv) application?

但除此之外,您应该了解属性的范围:它的范围是 (i) 页面、(ii) 请求、(iii) 会话还是 (iv) 应用程序?

I don't know the default scope off-hand, but you might want to look into that.

我不知道现成的默认范围,但您可能想研究一下。

回答by Sagar Sane

You need request.getAttribute()instead of request.getParameter()

你需要request.getAttribute()而不是request.getParameter()