class PageHistoryService {

    public void recordPageHistory(HttpServletRequest request, HttpServletResponse response, ModelAndView modelAndView, HandlerMethod handler) {
        Deque<PageHistory> history = getPageHistory(request).orElse(new LinkedList<>());
        while (history.contains(new PageHistory(request.getRequestURI()))) {
            history.pop();
        }

        if (handler.hasMethodAnnotation(NavigationRoot.class)) {
            history.clear();
        }

        if (!history.isEmpty()) {
            modelAndView.getModel().put("cookieBackLinkUrl", history.peek().getUrl());
            modelAndView.getModel().put("cookieBackLinkText", history.peek().getName());
        }

        if (!ERROR.equals(request.getDispatcherType())) {
            history.push(new PageHistory(request.getRequestURI()));
            encodedCookieService.saveToCookie(response, PAGE_HISTORY_COOKIE_NAME, JsonUtil.getSerializedObject(history));
        }
    }

}