简体   繁体   English

Servlets-Session属性变为NULL

[英]Servlets-Session attribute becoming NULL

I am new to servlets and jsp. 我是servlet和jsp的新手。 In my program the flow is as below: 在我的程序中,流程如下:

loginpage.html -> controller (servlet - here I created session like this) loginpage.html > controllerloginpage.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 ( now it shows uid value as null)-> view_customers.jsp (need uid value here but its null ). -> create_user.html > conroller (现在将uid值显示为null)-> view_customers.jsp (此处需要uid值,但为null )。

How to avoid session attribute from becoming null? 如何避免会话属性变为空? Thanks in advance! 提前致谢!

How to avoid session attribute from becoming null? 如何避免会话属性变为空?

You can monitor the attribute state (added/removed/replaced) in session scope using HttpSessionAttributeListener . 您可以使用HttpSessionAttributeListener监视session scope的属性状态(添加/删除/替换)。

Sample code: 样例代码:

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: (add below line in web.xml) web.xml :(在web.xml中的行下方添加)

<listener>
    <listener-class>com.x.y.z.MySessionAttributeListener</listener-class>
</listener>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM