繁体   English   中英

如何保持会话属性

[英]How to keep alive a session attribute

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

为了执行查找,我需要一个我在会话中放入不同servlet的loginresult对象。

这是在登录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.)查看JSESSIONID cookie的内容。 大多数浏览器都做到这一点。 如果内容更改,您将收到另一个会话。

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

如果要获得新会话,则必须将其范围缩小到配置问题(Tomcat,web.xml,上下文片段等)或应用程序问题。 如果是配置问题,则该问题应该在您提到的页面之外的其他页面上重复出现。

还可以考虑使用getSession(false),如果尚不存在,则不会创建新会话。 如果您从中得到空值,则表明会话正在超时。

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

暂无
暂无

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

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