pooney
article thumbnail

Interceptor에서  특정 페이지로 이동시키기 위하여 Redirect를  사용해야 하는 경우가 흔히 발생한다 가령 예로 로그인 여부를 확인 한다거나 등이 존재하는데 이때 흔히 착 착각 하는 것이 Interceptor에서 sendRresponse.sendRedirect(); 를 사용하면 모든 작업을 끝내고 바로 내가 원하는 페이지로 Redirect를 수행한다고 착각하는것이다. 하지만 모든 작업을 끝내는 것이 아닌 모든 작업을 완료하고 Redirect 작업을 수행하는 것이다. 

 

 

 

Interceptor의 preHandle 리턴 값 변경 전

 

0.1. Controller 

<java />
@Controller public class HomeController { //첫번째 @RequestMapping(value = "first", method = RequestMethod.GET) public String first() { System.out.println("first"); return "first"; } //두번째 @RequestMapping(value = "second", method = RequestMethod.GET) public String second() { System.out.println("second"); return "second"; } }

 

 

1. Interceptor

 

<java />
public class LoginIterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("pre+++++++"); response.sendRedirect(request.getContextPath()+"/second"); System.out.println("리다이렉트 이후 벌어지는 일 "); return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("after+++++++"); System.out.println(modelAndView.getViewName()); return; } }

 

 

2. 실행화면  (http://localhost:8093/controller/first 를 입력 후 second로 리다이텍트)

 

 

 

3. 결과화면 

 

 

 

 

-false로-바꿔-해당-작업을-종료시키면-해결된다-" href="#article-3-1--prehandle()-에서-sendredirect를-수행-한-후에도--콘솔창을-보면-"리다이렉트-이후-벌어지는-일"-출력-되는-것을-볼-수-있다--즉-모든-작업을-완료하고-redirect-가-일어나는-것이다---이를-해결-하기-위해서는-리턴-값을-true-->-false로-바꿔-해당-작업을-종료시키면-해결된다-">3.1. preHandle() 에서 sendRedirect를 수행 한 후에도  콘솔창을 보면 "리다이렉트 이후 벌어지는 일" 출력 되는 것을 볼 수 있다. 즉 모든 작업을 완료하고 Redirect 가 일어나는 것이다.  이를 해결 하기 위해서는 리턴 값을 true -> false로 바꿔 해당 작업을 종료시키면 해결된다. 

 

 

 

 

 

 

 

 

 

 

 

Interceptor의 preHandle 리턴 값 변경 후

 

4. Interceptor 

<java />
public class LoginIterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("pre+++++++"); response.sendRedirect(request.getContextPath()+"/second"); System.out.println("리다이렉트 이후 벌어지는 일 "); return false; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("after+++++++"); System.out.println(modelAndView.getViewName()); return; } }

 

 

 

5. 실행화면  (http://localhost:8093/controller/first 를 입력 후 second로 리다이텍트)

 

 

6. 결과화면 

 

6.1. false로 변경하면 작업을 종료하고 바로 Redirect작업을 수행하는 것을 볼 수 있다.

 

profile

pooney

@pooney

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!