java arrayList e session jsp 的问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4628394/
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
Problem with arrayList e session jsp
提问by zp26
I have a problem with my program.
我的程序有问题。
I have a servlet; in this servlet save the session attribute
我有一个 servlet;在这个 servlet 中保存会话属性
ArrayList<Integer> list = new ArrayList<Integer>;
list.add(1);
request.getsession().setAttribute("list",list);
Now the attribute is a String and not an ArrayList. In fact when i try to do:
现在该属性是一个字符串而不是一个 ArrayList。事实上,当我尝试做:
request.getsession().getAttribute(list)
is a string and not an Array.
是一个字符串而不是一个数组。
I want an Array.
我想要一个数组。
Thanks
谢谢
回答by Vincent Ramdhanie
You have to cast when you get the attribute from the session like this:
当您从会话中获取属性时,您必须进行转换,如下所示:
ArrayList<Integer> list = (ArrayList<Integer>)request.getsession().getAttribute("list");
And the attributes in the session are stored in a map, that is why the key you used is a String and you have to use a string to retrieve the value.
并且会话中的属性存储在映射中,这就是为什么您使用的键是字符串并且您必须使用字符串来检索值的原因。
回答by Jigar Joshi
session.getAttribute(..)
returns Object
session.getAttribute(..)
回报 Object
You will have to cast it like
你必须把它像
List<Integer> list = (List<Integer>)request.getsession().getAttribute("list");
回答by BalusC
As answered in your previousquestions, just access it by EL in JSP.
正如您之前的问题所回答的那样,只需在 JSP 中通过 EL 访问它。
${list}
If you want to iterate over it, use JSTL c:forEach
:
如果要迭代它,请使用 JSTL c:forEach
:
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<c:forEach items="${list}" var="item">
${item}<br />
</c:forEach>