
요청을 처리한 컨트롤러가 논리 뷰 이름을 반환하면 DispatcherServlet → ViewResolver → View 순서로 화면 렌더링이 진행된다. 스프링은 전략 패턴으로 다양한 뷰 리졸버를 제공한다.
InternalResourceViewResolver
RequestDispatcher#forward로 렌더링prefix + viewName + suffixThymeleafViewResolver
prefix=resources/templates/, suffix=.html리졸버는 여러 개 등록 가능하며 Order에 따라 순차 시도한다.
String 타입으로 반환@GetMapping("string")
public String stringReturning(Model model) {
model.addAttribute("forwardMessage", "문자열로 뷰 이름 반환함...");
return "result"; // -> templates/result.html
}
<!-- templates/result.html -->
<h1 th:text="${forwardMessage}"></h1>
@GetMapping("string-redirect")
public String stringRedirect() {
return "redirect:/"; // 302 응답 후 재요청
}
RedirectAttributes로 flash 저장@GetMapping("string-redirect-attr")
public String stringRedirectFlashAttribute(RedirectAttributes rttr) {
rttr.addFlashAttribute("flashMessage1", "리다이렉트 attr 사용하여 redirect..");
return "redirect:/";
}
<script>
const msg = '[[${flashMessage1}]]';
if (msg) alert(msg); // 1회성 메시지
</script>
포인트
ModelAndView로 반환모델과 뷰를 한 객체에 담아 반환한다. forward/redirect 모두 동일하게 활용 가능.
@GetMapping("modelandview")
public ModelAndView modelAndViewReturning(ModelAndView mv) {
mv.addObject("forwardMessage", "ModelAndView를 이용한 모델과 뷰 반환");
mv.setViewName("result");
return mv;
}
@GetMapping("modelandview-redirect")
public ModelAndView modelAndViewRedirect(ModelAndView mv) {
mv.setViewName("redirect:/");
return mv;
}
@GetMapping("modelandview-redirect-attr")
public ModelAndView modelAndViewRedirectAttr(ModelAndView mv, RedirectAttributes rttr) {
rttr.addFlashAttribute("flashMessage2", "ModelAndView를 이용한 redirect attr");
mv.setViewName("redirect:/");
return mv;
}
<script>
const msg = '[[${flashMessage2}]]';
if (msg) alert(msg);
</script>
forward vs redirect
flash attribute
템플릿 경로
templates/ 기준 상대 경로 + .html 생략 관례리졸버 다중 등록
ThymeleafViewResolver의 prefix/suffix 규칙을 따른다