0
1

Springbootで特定のエンドポイントが実行されたらセッションを更新しないような実装をしてみる

Last updated at Posted at 2024-08-22

概要

一定時間ごとにAPIを実行してセッションが有効かどうかの判定がしたかった。
Filterを実装しセッション有効判定エンドポイント以外がアクセスされた場合はsetAttributeに現在の時間をセッションに設定しセッション有効判定エンドポイントがアクセスされた場合はセッションタイムアウトのチェックとセッションの無効化をおこなうようにしてみた。

@Component
public class SessionTimeoutFilter implements Filter {
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession();

        if (httpRequest.getRequestURI().endsWith("/session-timeout")) {
            // セッションタイムアウトのチェックとセッションの無効化
            checkAndInvalidateSession(session);
        } else {
            // 現在の時間をセッションに設定
            session.setAttribute("sessiontimeout", System.currentTimeMillis());
        }
        chain.doFilter(request, response);
    }

    private void checkAndInvalidateSession(HttpSession session) {
        long lastAccessTime = (long) session.getAttribute("sessiontimeout");
        if (lastAccessTime + 100000L <= System.currentTimeMillis()) {
            // 時間が来たらセッションを無効
            session.invalidate();
        }
    }
}

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1