如何更新session.setAttribute(name,value)值,其名称相同?

时间:2013-04-10 05:38:24

标签: java servlets

我有一种情况需要更新名称保持不变的setAttribute的值。考虑以下情况作为示例 - 假设我有三个JSP:abc.jsp,xyz.jsp,pqr.jsp。现在首先运行abc.jsp然后控制前进到xyz.jsp&然后转发到pqr.jsp。现在执行pqr.jspt后再次使用setAttribute上的更新值重新控制回xyz.jsp。
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.

1 个答案:

答案 0 :(得分:7)

再次使用setAttribute()将replace the value并调用必要的生命周期方法。

  

如果某个对象已绑定到此名称的实现HttpSessionBindingListener的会话,则会调用其HttpSessionBindingListener.valueUnbound方法。

您还可以使用removeAttribute()并再次设置具有相同名称的属性。如果通过'update'表示您希望更新对象而不是替换对象,则使用getAttribute()获取属性并在其上调用将改变对象的方法。