SpringMVC - Redirect

이건우·2025년 3월 20일

웹 프로그래밍

목록 보기
27/43

Spring MVC에서 Redirect는 클라이언트가 다른 URL로 이동하도록
서버가 응답하는 방식으로, Spring MVC에서는 redirect: 접두사를 사용하여
리다이렉트를 쉽게 구현할 수 있습니다.


리다이렉트의 개념

리다이렉트는 클라이언트(웹 브라우저)에게 새로운 URL로 이동하도록 지시하는 HTTP 응답으로, 보통 HTTP 상태 코드 302(Found) 또는 301(Moved Permanently)과 함께 Location 헤더에 새로운 URL을 포함하여 응답합니다.

리다이렉트 과정

  1. 클라이언트가 서버에 A 요청을 보낸다.
  2. 서버는 redirect:를 사용하여 클라이언트에게 B URL로 이동하라고 응답한다.
  3. 클라이언트는 B URL로 다시 요청을 보낸다.
  4. 서버는 B URL에 대한 응답을 처리하여 클라이언트에게 반환한다.

리다이렉트 특징

  • 클라이언트가 새로운 요청을 보내므로,
    기존 요청 데이터(Request Parameter, Model 데이터 등) 는 유지되지 않는다.
  • 브라우저의 주소(URL)가 변경된다.
  • HTTP 상태 코드 302 Found 또는 301 Moved Permanently를 사용한다.

Spring MVC에서 Redirect 사용법

redirect: 접두사 사용

@Controller
public class RedirectController {

    @GetMapping("/redirectExample")
    public String redirectExample() {
        return "redirect:/targetPage"; // "/targetPage"로 리다이렉트
    }
}

동작 방식

  1. 클라이언트가 /redirectExample 요청을 보냄.
  2. redirect:/targetPage를 반환하면서 302 응답을 보냄.
  3. 클라이언트가 /targetPage로 다시 요청을 보냄.
  4. /targetPage에서 처리된 결과를 클라이언트가 받음.

특징

  • redirect: 접두사를 사용하면 Spring이 자동으로 HTTP 302 상태 코드를 설정함.
  • 브라우저의 URL이 변경됨.
  • Model 데이터를 유지하지 않음.

리다이렉트 시 쿼리 파라미터 전달

@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;
}
  • redirectAttributes.addAttribute("name", "gunwoo")
    ?name=gunwoo 형태로 URL에 포함.
  • redirectAttributes.addFlashAttribute("message", "Welcome!")
    일회성 세션 데이터로 저장됨 (한 번 사용 후 사라짐)
  • @ModelAttribute("message")로 FlashAttribute에 저장된 값을 가져올 수 있음.

HttpServletResponse.sendRedirect() 사용

Spring MVC의 기능이 아니라 순수한 서블릿 방식으로 리다이렉트하는 방식.

@GetMapping("/manualRedirect")
public void manualRedirect(HttpServletResponse response) throws IOException {
    response.sendRedirect("/targetPage");
}
  • response.sendRedirect("/targetPage")는 직접 HTTP 응답을 제어하는 방식.
  • Spring의 redirect: 방식보다 직접적인 서블릿 제어가 필요함.

리다이렉트를 효과적으로 사용하여 페이지의 이동을 좀 더 자연스럽게 구현해보자!

profile
새싹개발자

0개의 댓글