Somnath Kayal
Somnath Kayal

Reputation: 393

How to update session.setAttribute(name,value) value, where the name is same?

I have a situation where I need to update the value of a setAttribute where the name remains same. Consider the following situation as example-
Suppose I have three JSP: abc.jsp, xyz.jsp, pqr.jsp. Now at first abc.jsp runs then control forward to xyz.jsp & then forward to pqr.jsp. Now after execute pqr.jspthe control back to xyz.jsp again with a updated value at setAttribute.
abc.jsp:

ArrayList<Books> getSupplyStatus=new ArrayList<Books>();
JavaBean javaBean=new JavaBean();
session=request.getSession(false);
getSupplyStatus=javaBean.getSupplyStatus(memberID); //It returns a ArrayList 
if(!getSupplyStatus.isEmpty())
{
  session.setAttribute("UpdatedBooklist", getSupplyStatus);
  request.getRequestDispatcher("xyz.jsp").forward(request, response);
}

xyz.jsp:

session=request.getSession(false);
ArrayList<Books> getSupplyStatus=(ArrayList<Books>) session.getAttribute("UpdatedBooklist");
// some operations & forward to pqr.jsp

pqr.jsp:

// in this jsp new ArrayList<Books> will be prodeuced
// & I need to bound the value of "UpdatedBooklist" with 
// which is set in abc.jsp,
// and previous value must be override & then forward to xyz.jsp again
// In xyz.jsp we recieve the updated value.

Upvotes: 3

Views: 13861

Answers (1)

Deepak Bala
Deepak Bala

Reputation: 11185

Using setAttribute() again will replace the value and call the necessary lifecycle methods.

If an object was already bound to this session of this name that implements HttpSessionBindingListener, its HttpSessionBindingListener.valueUnbound method is called.

You can also use removeAttribute() and set an attribute with the same name again. If by 'update' you mean you want the object updated and not replaced, then get the attribute with getAttribute() and call methods on it that will mutate the object.

Upvotes: 7

Related Questions