如何保持会话属性

时间:2010-12-29 15:57:16

标签: java web-applications session-variables tomcat

我有一个“查找”html页面,它与一个处理某些功能并将结果发送到jsp页面的java HttpServlet类一起工作。

要执行查找,我需要一个loginresult对象,我将该会话放在另一个servlet中。

这是登录servlet中发生的事情:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        // get attributes that were filled in on the login webpage
        request.getAttribute("username");
        request.getAttribute("password");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        LoginManager loginManager = new LoginManager(username.trim(), password.trim());
        if (loginManager.doLogin() == true) {
            javax.servlet.http.HttpSession session = request.getSession();
            session.setAttribute("loginResult", loginManager.getLoginResult());
            session.setAttribute("binding", loginManager.getBinding());
            response.sendRedirect("lookup.html");

这是查找servlet上发生的事情

request.setCharacterEncoding("UTF-8");
            response.setContentType("text/html");
            javax.servlet.http.HttpSession session = request.getSession();
            LoginResult lr = (LoginResult) session.getAttribute("loginResult");
            if(lr == null)
            {
                throw new Exception("Your session has expired, please log in again");
            }

            // some look up code

            RequestDispatcher dispatcher = request.getRequestDispatcher("result.jsp");
            request.setAttribute("result", result);
            request.setAttribute("question", question);
            request.setAttribute("xml", xml);
            dispatcher.forward(request, response);

在我的jsp页面中是一个输入按钮,它执行以下操作:ONCLICK =“window.location.href ='lookup.html'”/>

有时当我离开我的结果页面没有聚焦或最小化或者我等待太久时,我点击返回查找页面,看来我的loginresult对象== null。 所以在我看来它接近过期了。虽然我认为Apache Tomcat服务器可以使会话保持30分钟标准。

有什么猜测我的会话属性消失了吗?

1 个答案:

答案 0 :(得分:1)

首先,您应该确定您是否真正获得了相同的会话。我有两种简单的方法可以做到这一点。

1。)查看JSESSIONID cookie的内容。大多数浏览器使这一点变得微不足道如果内容发生变化,您将收到不同的会话。

2。)您可以尝试插入HttpSessionListener来记录会话被销毁的时间。

如果您要获得新会话,则必须将其缩小到配置问题(Tomcat,web.xml,上下文代码等)或应用程序问题。如果这是一个配置问题,那么问题应该在你提到的其他页面上重复。

还要考虑使用getSession(false),如果尚未创建新会话,则不会创建新会话。如果你从中得到null,那么这是你的会话超时的另一个指标。

如果您确定您拥有相同的会话,但由于某些奇怪的原因属性正在消失,您可以实现HttpSessionAttributeListener以及从会话中删除项目时的日志或断点。