有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何在Servlet中完全消除会话?

我有两个JSP页面:登录和索引 还有三个servlet:LoginServlet、LogoutServlet和Profile .现在我只想在会话中有内容时查看我的个人资料。在LoginServlet的post()中,我编写了在属性中设置的逻辑,在LogoutServlet的get()中,我调用invalidate()方法来删除会话。现在,当我直接进入配置文件url而不调用登录页面时,如果配置文件被阻塞。类被执行,而不是在会话中什么都没有的情况下执行。getAttribute(“名称”)

获取配置文件的方法:

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();
    req.getRequestDispatcher("link.jsp").include(req, resp);  
    HttpSession session = req.getSession(false);
    if (session != null) {
        System.out.println("Session is not null");
        out.print("Hello " + session.getAttribute("name"));
    } else {
        out.print("Please login");
        req.getRequestDispatcher("Login.jsp").include(req, resp);
    }
    out.close();
}

我需要做些额外的事情来彻底消除这个环节


共 (1) 个答案

  1. # 1 楼答案

    在登录类中,请使用以下内容:

    if (isValidUser(userName, userPass)) {
        request.getSession(true);
        request.getSession.setAttribute("isLogged", true);
    }
    

    在LogoutServlet类中,使用以下代码:

    protected void doPost(HttpServletRequest request, ....
    
        request.getSession().invalidate(); // Vanish session completely
        ....
    

    在Profile类中,要验证用户是否已登录,请使用以下命令:

    if ((Boolean) request.getSession.getAttribute("isLogged") != null) {
        ... // user is logged
    } else
        redirectToIndexPage();