[참고] Redirect와 Forward
redirect
: http 상태 302, 새로운 URL이 Location header에 찍혀서 응답을 받음. browser/client 는 새로운 url에 대해 request를 날리게 됨- • 302(임시 이동): 현재 서버가 다른 위치의 페이지로 요청에 응답하고 있지만 요청자는 향후 요청 시 원래 위치를 계속 사용해야 한다.
- redirect를 쓰는 예시:
- form data를 POST 할 때
- 클라이어트가 요청한 페이지 혹은 리소스가 기존의 장소가 아닌 다른 곳으로 옮겨 졌을 때 해당 리소스로 안내를 하는 것
forward
: 오로지 서버 쪽에서 일어나게 되는 과정임. 서블릿 컨테이너는 해당 request를 target URL로 넘겨주게 됨. browser에서 URL이 바뀌지는 않음
ㅤ | Redirect | Forward |
클라이언트의 추가 Action | O | X |
URL 변화 | O | X |
Redirect
@Controller @RequestMapping("/") public class RedirectController { @GetMapping("/redirectWithRedirectPrefix") public ModelAndView redirectWithUsingRedirectPrefix(ModelMap model) { model.addAttribute("attribute", "redirectWithRedirectPrefix"); return new ModelAndView("redirect:/redirectedUrl", model); } } curl -i http://localhost:8080/spring-rest/redirectWithRedirectPrefix HTTP/1.1 302 Found Server: Apache-Coyote/1.1 Location: http://localhost:8080/spring-rest/redirectedUrl?attribute=redirectWithRedirectPrefix
Forward
@Controller @RequestMapping("/") public class RedirectController { @GetMapping("/forwardWithForwardPrefix") public ModelAndView redirectWithUsingForwardPrefix(ModelMap model) { model.addAttribute("attribute", "forwardWithForwardPrefix"); return new ModelAndView("forward:/redirectedUrl", model); } } curl -I http://localhost:8080/spring-rest/forwardWithForwardPrefix
비교
- redirect에서는 2번의 요청이 생기는데 반해 forward는 client에서는 요청을 한번만 보내게 되는 것임