0

My problem is simple but I am confused with this please help me.

In a JSP, I am receiving an Attribute(idsList) from Servlet1 and I want to send this Attribute(idsList) to another servlet, Servlet2 but I can do this using session.setAttribute(). My trouble is, how can we send to Servlet2 in JSP itself?

Here is my code, but it's not working because the same request is used to set and get. Please do the favour.

In Servlet1:

request.setAttribute("idsList",idsList);---is null

In JSP

List<Integer> idsList =(List<Integer>)request.getAttribute("idsList");
System.out.println("size of ids list :"+idsList.size());
request.setAttribute("idsList",idsList);

In Servlet2 :

request.getAttribute("idsList");---is null
Pabru
  • 231
  • 2
  • 7
sunleo
  • 10,589
  • 35
  • 116
  • 196

3 Answers3

7

Forward your request using RequestDispatcher as shown below:

request.setAttribute("idsList",idsList);
RequestDispatcher rd = getServletContext().getRequestDispatcher("servlet2");
rd.forward(request, response);

You can use request.getAttribute("idsList") on servlet2.

Do not use response.sendRedirect() to send request object.

EDIT :

I found a comment below your question:

r u getting value in JSP using setAttribute? YES

Generally, JSP are used as a VIEW perspective, so,

IT SHOULD NOT CONTAIN BUSINESS LOGIC

Pabru
  • 231
  • 2
  • 7
Parth Soni
  • 11,158
  • 4
  • 32
  • 54
1

If you use RequestDispatcher for forwarding the request, then the request object is same.

But if you use response.sendRedirect(), a new request object will be created and the attributes set in previous request object cannot be retrieved.

Munesh
  • 1,509
  • 3
  • 20
  • 46
1

The request object in which you are setting the attribute, request will end and a new request object will be created when you submit your jsp.

You can either use the session to set the attribute, or you can have a hidden field in the form, which when submitted to the servlet

And as Munesh is suggesting, you need to reconfirm that, how you have forwarded the control to the JSP 1) SendRedirect 2) Request Dispatcher

Sashi Kant
  • 13,277
  • 9
  • 44
  • 71