Passing ArrayList from jsp to servlet on form submit -
i trying pass arraylist object jsp page on submitting form 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 run code , getting nullpointerexception @ line "system.out.print(al.get(0))".
can tell me why happening?
also should if want use al object in servlet ?
you getting nullpointerexception because
request.getattribute("allproducts"); returns null
and calling method al.get(0) on null object.
why did al null?
when submit form new request submitted resulting in flush of old request object. new request object not contain array list had set on jsp.
oracle docs nullpointerexception
public class nullpointerexception extends runtimeexception thrown when application attempts use null in case object required. these include:
- calling instance method of null object.
- accessing or modifying field of null object.
- taking length of null if array.
- accessing or modifying slots of null if array.
- throwing null if throwable value.
side note
- do not write scriptlets in jsp, because scriptlets shouldn't used in jsps more decade. learn jsp el, jstl, , use servlet java code. how avoid java code in jsp-files?
Comments
Post a Comment