3

I have a problem with my program.

I have a servlet; in this servlet save the session attribute

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:

request.getsession().getAttribute(list)

is a string and not an Array.

I want an Array.

Thanks

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
zp26
  • 1,507
  • 8
  • 20
  • 38

3 Answers3

5

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.

Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
  • @zp26 What is the problem with it? – Vincent Ramdhanie Jan 07 '11 at 17:38
  • Multiple markers at this line - Type safety: Unchecked cast from Object to ArrayList – zp26 Jan 07 '11 at 17:39
  • @zp26 Fixed. Also org.life.java - Jigar Joshi had it correct all along. – Vincent Ramdhanie Jan 07 '11 at 17:41
  • @zp26 this is not a problem.. Just change the cast to ArrayList list = (ArrayList)object and the "Unchecked" will disappear. "The local variable.." that means you are not using the variable along the rest of the code (or sometimes it bugs when you use it inside some conditions, cant remember very well wich ones). – Renan Jan 07 '11 at 17:43
  • Sorry but the Unchecked cast don't disappear. – zp26 Jan 07 '11 at 17:45
  • The unchecked cast is a warning, not an error. It's telling you that you're casting a non-generic object (`request.getsession().getAttribute("list")`) to a generic object (`ArrayList`). You might be able to get rid of it by adding `<%! @SuppressWarnings("unchecked") %>` at the top of your jsp. – matt Jan 07 '11 at 18:40
1

session.getAttribute(..) returns Object

You will have to cast it like

List<Integer> list = (List<Integer>)request.getsession().getAttribute("list");
jmj
  • 237,923
  • 42
  • 401
  • 438
1

As answered in your previous questions, just access it by EL in JSP.

${list}

If you want to iterate over it, use JSTL c:forEach:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<c:forEach items="${list}" var="item">
    ${item}<br />
</c:forEach>

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555