java 会话验证过滤器在会话过期时注销用户

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7370885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 19:42:24  来源:igfitidea点击:

Session validation filter which logs off the user when session is expired

javaservletsloginservlet-filters

提问by BalusC

I have a session validation Filter which logs off the user when session is expired.

我有一个会话验证过滤器,它在会话过期时注销用户。

Here is a piece of code but this is not working. Not working means this is not redirecting to the login page even if the session expires.

这是一段代码,但这不起作用。不工作意味着即使会话过期也不会重定向到登录页面。

Please help me to resolve this issue.

请帮我解决这个问题。

public void doFilter(ServletRequest request, ServletResponse response, 
        FilterChain chain) throws IOException, ServletException {  
    HttpServletResponse res = (HttpServletResponse) response;  
    HttpServletRequest req = (HttpServletRequest) request;  

    HttpSession s = req.getSession(false);  

    if (s==null)
    {
        //redirect to login page with session expiry message   
    } else {  
        chain.doFilter(request, response);  
    }  
}

回答by BalusC

I have a session validation Filter which logs off the user when session is expired.

我有一个会话验证过滤器,它在会话过期时注销用户。

This makes honestly no utter sense. If you store the logged-in user as an attribute of the session and intercept the "logged-in" status based on the presence of the logged-in user in the session, then you do not need to manually logout the user at all when the session is expired. When the session expires, all its attribtues will get lost anyway and hence the user will be "automagically" logged out.

老实说,这完全没有意义。如果你将登录用户存储为会话的一个属性,并根据登录用户在会话中的存在来拦截“登录”状态,那么当你完全不需要手动注销用户时会话已过期。当会话过期时,它的所有属性无论如何都会丢失,因此用户将“自动”注销。

Here's an example of how you can login the user in the doPost()of a servletwhich is invoked by a POST submit of the login form JSP.

这里是你如何登录用户在一个例子doPost()一的小服务程序是由一个POST调用提交登录表单的JSP

String username = request.getParameter("username");
String password = request.getParameter("password");
User user = userService.find(username, password);

if (user != null) {
    request.getSession().setAttribute("user", user); // Login user.
    response.sendRedirect("userhome"); // Redirect to user home page.
} else {
    request.setAttribute("errormessage", "Unknown login, try again"); // Set error message.
    request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Redisplay login form.
}

You see, when the login is valid, the user is stored as a session attribute. The remnant of your code could just check if it is null or not to determine if the user is logged in. Whenever the session expires, it automatically becomes null.

您会看到,当登录有效时,用户将存储为会话属性。您的代码的剩余部分可以只检查它是否为空以确定用户是否已登录。每当会话过期时,它会自动变为空。



this is not redirecting to the login page , even if the session expires

即使会话过期,这也不会重定向到登录页面

I have no idea what you're trying to do since the initial functional requirement makes no sense. However, there exist two common functional requirements related to session expiration and the login page. I guess that you actuallyneed either one of them:

我不知道您要做什么,因为最初的功能要求毫无意义。但是,存在与会话过期和登录页面相关的两个常见功能需求。我想您实际上需要其中之一:

  1. "How do I redirect the visitor to the login page when he requests a page which is restricted to logged-in users?"

    You need to create a filterand map it on the (common) URL pattern of the restricted page(s). In the filter, just check if the user is present in session and then continue the chain, else redirect to login page.

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);
    
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect("login"); // No logged-in user found, so redirect to login page.
        } else {
            chain.doFilter(req, res); // Logged-in user found, so just continue request.
        }
    }
    

  2. "How do I automatically redirect the currently opened page to the login page when the session expires?"

    Use the <meta>refresh in combination with HttpSession#getMaxInactiveInterval().

    <meta http-equiv="refresh" content="${pageContext.session.maxInactiveInterval};url=sessionexpired.jsp">
    

    This will automatically redirect the current page to the given urlwhenever the session expires. The ${pageContext.session.maxInactiveInterval}expression will inline the session expiration time in seconds, which is exactly what the contentattribute needs.

  1. “当访问者请求仅限登录用户访问的页面时,我如何将访问者重定向到登录页面?”

    您需要创建一个过滤器并将其映射到受限页面的(通用)URL 模式。在过滤器中,只需检查用户是否存在于会话中,然后继续链,否则重定向到登录页面。

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);
    
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect("login"); // No logged-in user found, so redirect to login page.
        } else {
            chain.doFilter(req, res); // Logged-in user found, so just continue request.
        }
    }
    

  2. “如何在会话过期时自动将当前打开的页面重定向到登录页面?”

    <meta>结合使用刷新HttpSession#getMaxInactiveInterval()

    <meta http-equiv="refresh" content="${pageContext.session.maxInactiveInterval};url=sessionexpired.jsp">
    

    url每当会话到期时,这将自动将当前页面重定向到给定的页面。该${pageContext.session.maxInactiveInterval}表达式将以秒为单位内联会话到期时间,这正是该content属性所需要的。