简体   繁体   中英

Servlets-Session attribute becoming NULL

I am new to servlets and jsp. In my program the flow is as below:

loginpage.html -> controller (servlet - here I created session like this)

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 ).

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 .

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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