[英]Servlets-Session attribute becoming NULL
我是servlet和jsp的新手。 在我的程序中,流程如下:
loginpage.html
> controller
( loginpage.html
在這里我創建了這樣的會話)
HttpSession session = request.getSession(true);
session.setAttribute("uid", uname);
System.out.println("session:"+session.getAttribute("uid"));// shows the value of uid
-> create_user.html
> conroller
(現在將uid
值顯示為null)-> view_customers.jsp
(此處需要uid
值,但為null )。
如何避免會話屬性變為空? 提前致謝!
如何避免會話屬性變為空?
您可以使用
HttpSessionAttributeListener
監視session scope
的屬性狀態(添加/刪除/替換)。
樣例代碼:
public class MySessionAttributeListener implements HttpSessionAttributeListener {
public MySessionAttributeListener() {
}
public void attributeAdded(HttpSessionBindingEvent sessionBindingEvent) {
// Get the session
HttpSession session = sessionBindingEvent.getSession();
// Log some information
System.out.println("[SessionAttr] " + new java.util.Date()
+ " Attribute added, session " + session + ": " + sessionBindingEvent.getName()
+ "=" + sessionBindingEvent.getValue());
}
public void attributeRemoved(HttpSessionBindingEvent sessionBindingEvent) {
// Get the session
HttpSession session = sessionBindingEvent.getSession();
// Log some information
System.out.println("[SessionAttr] " + new java.util.Date()
+ " Attribute removed, session " + session + ": "
+ sessionBindingEvent.getName());
}
public void attributeReplaced(HttpSessionBindingEvent sessionBindingEvent) {
// Get the session
HttpSession session = sessionBindingEvent.getSession();
// Log some information
System.out.println("[SessionAttr] " + new java.util.Date()
+ " Attribute replaced, session " + session + ": "
+ sessionBindingEvent.getName() + "=" + sessionBindingEvent.getValue());
}
}
web.xml :(在web.xml中的行下方添加)
<listener>
<listener-class>com.x.y.z.MySessionAttributeListener</listener-class>
</listener>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.