Servlets-Session属性变为NULL

时间:2014-04-27 19:40:56

标签: java jsp session servlets

我是servlets和jsp的新手。在我的程序中,流程如下:

loginpage.html - > controller(servlet - 这里我创建了这样的会话)

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

如何避免会话属性变为空?提前谢谢!

1 个答案:

答案 0 :(得分:0)

如何避免会话属性变为空?

  

您可以使用session scopeHttpSessionAttributeListener中监控属性状态(添加/删除/替换)。

示例代码:

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>