Interceptor에서 특정 페이지로 이동시키기 위하여 Redirect를 사용해야 하는 경우가 흔히 발생한다 가령 예로 로그인 여부를 확인 한다거나 등이 존재하는데 이때 흔히 착 착각 하는 것이 Interceptor에서 sendRresponse.sendRedirect(); 를 사용하면 모든 작업을 끝내고 바로 내가 원하는 페이지로 Redirect를 수행한다고 착각하는것이다. 하지만 모든 작업을 끝내는 것이 아닌 모든 작업을 완료하고 Redirect 작업을 수행하는 것이다.
Interceptor의 preHandle 리턴 값 변경 전
Controller
@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";
}
}
Interceptor
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;
}
}
실행화면 (http://localhost:8093/controller/first 를 입력 후 second로 리다이텍트)
결과화면
preHandle() 에서 sendRedirect를 수행 한 후에도 콘솔창을 보면 "리다이렉트 이후 벌어지는 일" 출력 되는 것을 볼 수 있다. 즉 모든 작업을 완료하고 Redirect 가 일어나는 것이다. 이를 해결 하기 위해서는 리턴 값을 true -> false로 바꿔 해당 작업을 종료시키면 해결된다.
Interceptor의 preHandle 리턴 값 변경 후
Interceptor
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;
}
}
실행화면 (http://localhost:8093/controller/first 를 입력 후 second로 리다이텍트)
결과화면
false로 변경하면 작업을 종료하고 바로 Redirect작업을 수행하는 것을 볼 수 있다.
'Spring' 카테고리의 다른 글
Spring Mapped Statements collection does not contain value for 에러 (0) | 2020.05.05 |
---|---|
Spring mybatis 쿼리 리턴 유형 (0) | 2020.05.05 |
Spring Interceptor에서 redirect 사용법 (2) | 2020.05.02 |
Spring Redirect&dispatcher를 이용한 포워딩 (0) | 2020.05.01 |
Spring 포워드 방법 (0) | 2020.05.01 |