java 如何更新 session.setAttribute(name,value) 值,其中名称相同?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15917792/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update session.setAttribute(name,value) value, where the name is same?
提问by Somnath Kayal
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:
我有一种情况,我需要更新名称保持不变的 setAttribute 的值。考虑以下情况作为示例 -
假设我有三个 JSP:abc.jsp、xyz.jsp、pqr.jsp。现在首先 abc.jsp 运行然后控制前进到 xyz.jsp & 然后前进到 pqr.jsp。现在在执行 pqr.jsp 之后,使用 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:
xyz.jsp:
session=request.getSession(false);
ArrayList<Books> getSupplyStatus=(ArrayList<Books>) session.getAttribute("UpdatedBooklist");
// some operations & forward to pqr.jsp
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.
回答by Deepak Bala
Using setAttribute() again will replace the valueand call the necessary lifecycle methods.
再次使用 setAttribute() 将替换该值并调用必要的生命周期方法。
If an object was already bound to this session of this name that implements HttpSessionBindingListener, its HttpSessionBindingListener.valueUnbound method is called.
如果对象已绑定到此名称的实现 HttpSessionBindingListener 的会话,则调用其 HttpSessionBindingListener.valueUnbound 方法。
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.
您还可以使用removeAttribute()并再次设置具有相同名称的属性。如果“更新”是指您希望对象被更新而不是被替换,那么获取属性getAttribute()
并在其上调用将改变对象的方法。