0

I want to retrieve the ArrayList from a JSP page to servlet when submitting the form on the JSP page. I am trying following code:

Code of Pass.jsp is:

<form action="GetListServlet">
<%
    ArrayList al=new ArrayList();
    al.add("Naman");
    al.add("Gupta");
    request.setAttribute("allnames", al); 
%>
<input type="submit" value="Show List"></form>

doGet() method of GetListServlet is :-

protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException 
{
    ArrayList al=(ArrayList)request.getAttribute("allnames");
    System.out.print(al.get(0));
} 

But I am getting NullPointerException at System.out.print(al.get(0)).

Can anyone tell me how can I get arraylist of jsp page on the servlet page ?

Martín Schonaker
  • 7,273
  • 4
  • 32
  • 55
user3532498
  • 21
  • 1
  • 4
  • Try this [link][1]. This gives a better solution. [1]: http://stackoverflow.com/questions/17988612/how-to-send-arraylist-from-jsp-to-servlet – Jayant Varshney Apr 14 '14 at 15:27
  • I think you have a general misconception of what `request` is. You should solve this problem in plain HTML and then attempt to make it dynamic. – Martín Schonaker Apr 14 '14 at 15:34

1 Answers1

0

Simplest solution is to not store your array into response and send it back to the server. Instead, store your list into session using session.setAttribute("allnames", al); and obtain it in similar way: ArrayList al=(ArrayList)request.getSession().getAttribute("allnames");. You don't have to send the array to the client and back again.

But if you really want to, you can store the array as list of hidden HTML input fields and then obtain them from servlet using String[] al=request.getParameterValues('allnames');.

Kojotak
  • 2,020
  • 2
  • 16
  • 29
  • 1
    Sorry for the down vote, but adding session here is going to make it more confusing and introduce a new set of problems. – Martín Schonaker Apr 14 '14 at 15:35
  • Please can you elaborate why using a session is confusing and what's wrong with hidden form fields and obtaining all values for one parameter? The question is obviously about passing a list of data from one request to another. – Kojotak Apr 15 '14 at 07:04