티스토리 뷰

728x90

https://middleearth.tistory.com/22

 

스프링 시큐리티로 로그인 이후에 현재 페이지로 되돌아오는 방법

타임리프에서 아래와 같이 input을 받고 action으로 값을 올려준다. 장바구니 바로구매 해당 이름을 파라미터로 받는다. GET 요청이므로 body는 사용하지 않는 것이 좋다. @GetMapping("/login") public String l

middleearth.tistory.com

위 방법을 같이 참고바람

 

 

form의 input으로 현재 URL의 위치와 scrollY를 같이 보내주게 하고 hidden으로 숨겨둔다.

그리고 버튼이 눌렸을때 getScrollY() 함수가 실행되도록 한다.

<div class="col-2" sec:authorize="!isAuthenticated()">
                    <form method="get" th:action="@{/auth/login}">
                        <input type="hidden" th:name="scrollY" id="scrollY">
                        <input type="hidden" th:name="requestURI" th:value="${#httpServletRequest.requestURI}">
                        <button class="btn btn-primary btn-lg" onclick="getScrollY()">Q&A 작성</button>
                    </form>
                </div>

 

getScrollY 함수는 다음과 같다. 여기서 고정된 값은 window.scrollY(window 생략 가능)이며 나머지는 자유롭게 작성해도 된다.

function getScrollY() {
                document.getElementById('scrollY').value = window.scrollY;
            }

 

RequestParam으로 값을 받고 Session에 넣어둔다.

@GetMapping("/login")
    public String login(@RequestParam(name = "requestURI", required = false) String requestURI, @RequestParam(name = "scrollY", required = false) String scrollY, HttpServletRequest request, @CurrentUser User user) {
        request.getSession().setAttribute("requestURI", requestURI);
        request.getSession().setAttribute("scrollY", scrollY);
        if (user != null) {
            return "redirect:/";
        }

        return "auth/login";
    }

 

이 위에서 로그인이 처리된 이후에 다시 원래 페이지로 돌아온다.

 

그 이후 세션에서 값을 꺼내 HTML 아무데나 hidden으로 값을 매핑해둔다.

<input type="hidden" th:name="scrollY" id="scrollNow" th:value="${#session.getAttribute('scrollY')}">

 

window onload가 되는 시점에 <- 가장 중요하다

input에 매핑되었던 값을 받아와 scrollTo의 Y값에 넣어준다.

window.addEventListener('load', (e) => {

let scrollNow = document.getElementById('scrollNow').value;
                if (scrollNow == 0) {
                    window.scrollTo(0, window.scrollY);
                } else {
                window.scrollTo(0, scrollNow);
                }

 

여기까지 하면 전체적인 로직은 끝이다

하지만 Session에 값이 아직 남아있기때문에 계속 고정된 위치로 이동되게 될 것이다.

 

session에 남은 값을 제거하는 방법은 여러가지가 있겠지만 본인은 Interceptor를 사용했다.

 

 

렌더링이 전부 끝나면 실행되는 afterCompletion을 이용해서 세션값 제거 메서드를 작성하고 Component로 등록.

@Component
public class ScrollYInterceptor implements HandlerInterceptor {

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                                @Nullable Exception ex) throws Exception {
        request.getSession().removeAttribute("scrollY");
    }
}

 

마지막으로 특정 URL에만 실행될 수 있게 Interceptor를 등록하면 끝.

 

@Configuration
@RequiredArgsConstructor
public class ScrollYInterceptorRegister implements WebMvcConfigurer {

    private final ScrollYInterceptor ScrollYInterceptor;

    @Override
    public void addInterceptors(final InterceptorRegistry registry) {
        registry.addInterceptor(ScrollYInterceptor)
                .addPathPatterns("/item/**")
        ;
    }
}

 

 

위와 같이 하면 기본적인 흐름이 완성된다.

프론트에 조예가 깊다면 좀 더 쉽게 할 수 있는 방법이 있을듯하지만 백엔드쪽으로만 사고가 도는건 어쩔 수 없는 것같다..

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함