【问题标题】:Servlets-Session attribute becoming NULLServlets-Session 属性变为 NULL
【发布时间】:2014-04-27 19:40:55
【问题描述】:

我是 servlet 和 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)。 p>

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

【问题讨论】:

  • 先检查这段代码中你的uname是否为null。
  • Session#getSession(true);Session.getSession() 相同。上面写着:if the request does not have a session, creates one.
  • @ambarox uname 在代码中不为空...
  • @Braj Thnk u..我知道 dat..
  • 关于会话的用户侧信息由浏览器存储在cookies中。也许您的 cookie 要么被删除,要么一开始就没有创建。也许您的浏览器阻止了 cookie,或者您的应用程序设置的生存时间很短。也许您有类似于session.setMaxInactiveInterval(0) 的代码,或者在部署描述符(web.xml 文件)配置中,例如<session-config><session-timeout>0</session-timeout></session-config>

标签: java jsp session servlets


【解决方案1】:

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

您可以使用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>

【讨论】:

    猜你喜欢
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 2015-02-15
    相关资源
    最近更新 更多