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);
2
  • 1
    You can't cast an ArrayList<String> 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()]). Commented Jun 28, 2016 at 13:07
  • okay I could solve this, but it still tell me "null". I don't understand why? Commented Jun 28, 2016 at 18:20

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

okay I could solve this, but it still tell me "null". I don't understand why?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.