Spring MVC에서 Redirect는 클라이언트가 다른 URL로 이동하도록
서버가 응답하는 방식으로, Spring MVC에서는 redirect: 접두사를 사용하여
리다이렉트를 쉽게 구현할 수 있습니다.
리다이렉트는 클라이언트(웹 브라우저)에게 새로운 URL로 이동하도록 지시하는 HTTP 응답으로, 보통 HTTP 상태 코드 302(Found) 또는 301(Moved Permanently)과 함께 Location 헤더에 새로운 URL을 포함하여 응답합니다.
@Controller
public class RedirectController {
@GetMapping("/redirectExample")
public String redirectExample() {
return "redirect:/targetPage"; // "/targetPage"로 리다이렉트
}
}
@GetMapping("/redirectWithParams")
public String redirectWithParams(RedirectAttributes redirectAttributes) {
redirectAttributes.addAttribute("name", "gunwoo"); // URL 쿼리 파라미터로 전달됨
redirectAttributes.addFlashAttribute("message", "Welcome!"); // 일회성 세션 데이터
return "redirect:/targetPage";
}
@GetMapping("/targetPage")
@ResponseBody
public String targetPage(@RequestParam String name, @ModelAttribute("message") String message) {
return "Hello, " + name + "! Message: " + message;
}
Spring MVC의 기능이 아니라 순수한 서블릿 방식으로 리다이렉트하는 방식.
@GetMapping("/manualRedirect")
public void manualRedirect(HttpServletResponse response) throws IOException {
response.sendRedirect("/targetPage");
}
리다이렉트를 효과적으로 사용하여 페이지의 이동을 좀 더 자연스럽게 구현해보자!