0

I am trying to pass arraylist object from a jsp page on submitting a form to a servlet.

Code of jsp page :-

<form action="NewServlet">
<%
    ArrayList al=new ArrayList();
    al.add("abc");
    al.add("xyz");
    request.setAttribute("allproducts", al);
%>
<input type="submit" value="Show"></form> 

Code of NewServlet :-

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

When I run this code , I am getting NullPointerException at line "System.out.print(al.get(0))".

Can anyone tell me why is it happening?

Also what should I do if I want to use this al object in servlet ?

user3471460
  • 45
  • 1
  • 5

1 Answers1

1

You are getting NullPointerException because

request.getAttribute("allproducts");

returns null

And you are calling a method al.get(0) on null object.


Why did you get al null?

When you submit the form new request is submitted resulting in flush of your old request object. New request object does not contain the array list which you had set on JSP.


Oracle docs for NullPointerException

public class NullPointerException
             extends RuntimeException

Thrown when an application attempts to use null in a case where an object is required. These include:

  • Calling the instance method of a null object.
  • Accessing or modifying the field of a null object.
  • Taking the length of null as if it were an array.
  • Accessing or modifying the slots of null as if it were an array.
  • Throwing null as if it were a Throwable value.

Side Note

Community
  • 1
  • 1
Aniket Kulkarni
  • 12,825
  • 9
  • 67
  • 90
  • I want to use the araylist of jsp in servlet.Can you tell me how can I do so ? – user3471460 Apr 14 '14 at 14:38
  • @user3471460 : Iterate array list and create `hidden` fields. Give same name to each hidden field. In servlet access hidden fields with `request.getParameterVales("hidden_name");`, it returns you array. From array you can create array list in servlet. http://www.w3.org/TR/html-markup/input.hidden.html http://www.w3.org/wiki/HTML/Elements/input/hidden – Aniket Kulkarni Apr 15 '14 at 04:58