0

There is a Problem in my Project. I have a JSP page and a Java servlet. The servlet have to save a list with names in the session with session.setAttribute(). On the JSP page have to read from the session with session.getAttribute() and print out all names from the list with a for-loop. So the current problem is I don't know how to cast the Obect/ArrayList to a regular String array. I know there are much better ways to do this, but I have to do it this way.

Here is my code

Servlet:

private ArrayList<String> userlist = new ArrayList<String>(Arrays.asList("bla1","bla2","bla3","bla4")); // unsynchronisiert

public void addName(String name){
    userlist.add(name);
}   

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    addName(request.getParameter("username"));
    System.out.println(userlist);
    HttpSession session = request.getSession();
    session.setAttribute("userlist", userlist);
}

JSP:

String[] names = (String[]) session.getAttribute("userlist");
System.out.println(names);
BalusC
  • 992,635
  • 352
  • 3,478
  • 3,452
WeSt
  • 669
  • 3
  • 10
  • 24
  • 1
    You can't cast an ArrayList to a String[]. Why don't you cast it to ArrayList? If you need a String[] you then could parse it via list.toArray(new String[list.size()]). – Benjamin Schüller Jun 28 '16 at 13:07
  • okay I could solve this, but it still tell me "null". I don't understand why? – WeSt Jun 28 '16 at 18:20

1 Answers1

0

You are casting ArrayList into Array.you cant cast ArrayList into Array.

You need to Replace:
String[] names = (String[]) session.getAttribute("userlist");
with
ArrayList list= (ArrayList)session.getAttribute("userlist ");

and now iterate list and get data from it.

Kalpen Patel
  • 81
  • 10
  • okay I could solve this, but it still tell me "null". I don't understand why? – WeSt Jun 28 '16 at 18:20
  • please provide error log file. if it returns null than it means nothing is stored in session for that key(userlist). Or you are trying to fetch data before storing in session. – Kalpen Patel Jun 29 '16 at 09:05