SpringBoot

RedirectAttributes

똑똑한망치 2024. 5. 2. 19:53
728x90
반응형

1. RedirectAttributes

리디렉션을 수행할 때 한 컨트롤러 메서드에서 다른 컨트롤러 메서드로 Attributes를 전달하는데 이용되는 스프링 프레임워크의 인터페이스이다.

  • 리다이렉트(Redirect)는 사용자가 처음 요청한 URL이 아닌, 다른 URL로 보내는 것을 의미한다.
  • 일반적인 시나리오에서 Attributes 를 저장할 땐 Model의 addAttribute() 메서드를 많이 사용한다.

 

 

(1) RedirectAttributes 가 필요할 때

  • 예를 들어, 주문이 완료된 후 주문 결과 상세페이지로 리다이렉팅하고 그 결과를 보여주고 싶을 때 사용
    • 주문 처리가 끝났을 때 생성된 주문 번호를 리다이렉트 페이지 쪽으로 넘겨줄 수 있다

 

(2) RedirectAttributes 적용하고 데이터 저장하기

  • 간단히 RedirectAttributes 타입의 파라미터를 컨트롤러 메서드에 작성하면 된다.
  • 데이터 저장 시에는 redirectAttributes.addAttribute()redirectAttributes.addFlashAttribute() 두가지 중 하나를 사용할 수 있다.
  • 예시 코드
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

@Controller
public class MyController {
    @PostMapping("/submitForm")
    public String submitForm(@ModelAttribute("formData") FormData formData,
                             RedirectAttributes redirectAttributes) {
        // Your form processing logic here
        // ...

        // Add attributes to redirectAttributes
        redirectAttributes.addAttribute("orderNumber", "1010233");
        redirectAttributes.addFlashAttribute("message", "Order completed successfully.");

        // Redirect to another page
        return "redirect:/success";
    }
}

 

 

 

(3) addAttribute 와 addFlashAttribute 차이

redirectAttributes를 이용하여 데이터를 넘길 수 있는 2가지의 메서드이다.

  • addAttribute() 는 브라우저의 주소창에 보이게 URL에 추가하여 정보를 넘긴다.
    • 주소창에 보이는 만큼 짧은 정보, 이용자에게 노출되어도 상관 없는 정보를 넘기는데에 주로 사용한다.
    • 쿼리 파라미터가 있는 URL에 접근하는 한 여러 요청에 사용이 가능하다.
    • /targetURL?key=value 형식으로 전달된다.
  • addFlashAttribute() 는 세션에 저장되고 오직 다음 요청에서만 접근 가능하다.
    • 임시로 저장하는 방식이다.
    • 세션에 저장되어 사용된 뒤에 자동으로 삭제된다.
    • 검증 결과, 성공 실패 여부 메시지와 같이 임시로 사용되는 데이터를 다루는데 적합하다.
    • 또한, 주소창에 표기되지 않으므로 addAttribute()보다 폐쇄적이다.

 

 

 

(4) RedirectAttributes 로 넘긴 데이터 접근하기

  • addAttribute() 로 넘겼을 때,
    • URL로 넘어온만큼 기존처럼 @RequestParam 어노테이션을 사용하면 된다.
  • addFlashAttribute()로 넘겼을 때,
    • @ModelAttribute 어노테이션 사용하면 된다.
    • 다른 방법으로는 Model 오브젝트를 파라미터에서 이용하고 model.getAttribute()를 사용해도 된다.
  • 예시 코드
@Controller
public class MyController {
    @GetMapping("/success")
    public String success(@RequestParam("key") String key,
                          @ModelAttribute("message") String message,
                          Model model) {
        // Access query parameter
        System.out.println("Query parameter: " + key);

        // Access flash attribute
        System.out.println("Flash attribute: " + message);

        // Add the message to the model to display in the view
        model.addAttribute("message", message);
        return "success";
    }
}

 

반응형