且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-05 16:21:16


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






这是一个如何登录用户的示例POST调用的 servlet doPost()提交登录表单 JSP

  String username = request.getParameter(username); 
String password = request.getParameter(password);
用户user = userService.find(用户名,密码);

if(user!= null){
request.getSession()。setAttribute(user,user); //登录用户
response.sendRedirect(userhome); //重定向到用户主页。
} else {
request.setAttribute(errormessage,Unknown login,try again); //设置错误消息
request.getRequestDispatcher(/ WEB-INF / login.jsp)。forward(request,response); //重新显示登录表单。
}

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







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


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


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



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

      @Override 
    public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain)抛出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); //未找到登录用户,因此重定向到登录页面。
    } else {
    chain.doFilter(req,res); //找到登录用户,所以继续请求。
    }
    }





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



    使用< meta> HttpSession#getMaxInactiveInterval()



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

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



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);  
    }  
}

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 servlet which is invoked by a POST submit of the login form 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 actually need 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 filter and 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 url whenever the session expires. The ${pageContext.session.maxInactiveInterval} expression will inline the session expiration time in seconds, which is exactly what the content attribute needs.