Today
-
Yesterday
-
Total
-
  • Spring boot : 특정 URL에 접속했다가 다른 URL로 이동하는 세션 찾기 (with ChatGPT)
    개인 프로젝트/3. simple board 02 2023. 12. 21. 04:25

    회원가입을 구현하기 위한 설계를 해보던 와중에,
    닉네임 관련해서 중복되게 하지 않기 위해 이 구현이 필요하다고 생각되어 찾아보게 되었다.

    어떤 유저가 회원가입 진행 중 닉네임 중복 검사까지 통과하면 다른 신규 가입을 진행하려는 유저는 그 닉네임을 사용하지 못한다.


    이때 회원가입을 자의로(혹은 타의로) 종료한 경우 중복 검사를 통과한 유저의 세션이 끊긴다면 해당 닉네임을 다른 사람이 사용할 수 있게 구현해 보려는 의도이다.

     

    ChatGPT 답변

    아직 사용해 보지 못한 방법이지만, 이 방법으로 진행한다면 성공할 것 같아서 일단 먼저 해두는 기록!

     

    특정 URL에 접속하면 접속 중으로 표시하고, 그 후에 다른 URL로 이동하면 접속 종료로 표시하는 방법에 대해서는 Spring Boot에서 Interceptor와 세션을 활용하는 방법을 제시할 수 있습니다. 아래는 예시 코드입니다.

    1. Interceptor 구현:

    Interceptor를 사용하여 특정 URL에 접속 및 이동 동작을 처리합니다.

    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.HandlerInterceptor;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    @Component
    public class ConnectionInterceptor implements HandlerInterceptor {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            // 특정 URL에 접속할 때의 로직 수행
            HttpSession session = request.getSession();
            session.setAttribute("connectionStatus", "Connected"); // 접속 중으로 표시
    
            return true; // 계속 다음 단계로 진행
        }
    
        @Override
        public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
            // 요청이 완료된 후의 로직 수행
            HttpSession session = request.getSession();
            session.setAttribute("connectionStatus", "Disconnected"); // 접속 종료로 표시
        }
    }

    2. Interceptor 등록:

    Interceptor를 등록하여 특정 URL에만 적용하도록 설정합니다.

    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class WebConfig implements WebMvcConfigurer {
    
        private final ConnectionInterceptor connectionInterceptor;
    
        public WebConfig(ConnectionInterceptor connectionInterceptor) {
            this.connectionInterceptor = connectionInterceptor;
        }
    
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(connectionInterceptor)
                    .addPathPatterns("/specific-url/**"); // 특정 URL 패턴 지정
        }
    }

    위의 코드에서 /specific-url로 시작하는 URL에 접속하면 ConnectionInterceptorpreHandle 메서드가 호출되어 세션에 "Connected"로 표시됩니다. 이후 다른 URL로 이동하면 afterCompletion 메서드가 호출되어 세션에 "Disconnected"로 표시됩니다.

    이러한 방법으로 특정 URL에 접속 및 이동 동작을 추적하고 세션을 활용하여 상태를 표시할 수 있습니다. 이는 사용자의 접속 상태를 추적하는 기본적인 방법 중 하나일 뿐이며, 실제 프로덕션 환경에서는 보안과 성능에 대한 고려가 필요합니다.

Designed by Tistory / Custom by 얼거스