KH/Spring

[Spring] redirect 객체 전달 : RedirectAttributes

오늘의 진 2022. 12. 1. 14:19

 

Redirect시 데이터를 전달할수 있는 방법 

  • RedirectAttributes 클래스를 사용하여 전달한다. 
  • redirect시 RedierctAttributes클래스를 이용해 효과적으로 alert 창을 띄울 수도있다. 

 

1.addAttribute

@RequestMapping(value="/aaa/bbb/ddd.do", method =RequestMethod.POST)
public String test(ModelMap model, RedirectAttributes rttr) throws Exception{
    
    String message ="안녕.";
    rttr.addAttribute("message", message);
    
    return "redirect:/home";
}

이런식으로 하면 redirect에 message값을 담아서 전달 할 수 있다. 

그런데 아래와 같이 URL에 데이터가 노출된다. 

/home?message=안녕.
cs

 

2.addFlashAttribute 

addFlashAttribute 는 Post 형식으로 데이터 전달 

데이터가 한번만 사용된다. 

@RequestMapping(value="/aaa/bbb/ddd.do", method =RequestMethod.POST)
public String test(ModelMap model, RedirectAttributes rttr) throws Exception{
    
    String message ="안녕.";
    rttr.addFlashAttribute("message", message);
    
    return "redirect:/home";
}

addFlashAttribute는 String, list, map등 여러 타입을 전달 가능하다.

그런데 String 전달시 특히 유용. 

home.jsp 파일로 message가 전달되는데 이때 view 쪽에서 받아서 사용할때는 ${message} 로 받을 수 있다. 

 

만약 Object 타입을 담아서 보내는경우

RequestContextUtils.getInputFlashMap(request) 를 이용해서 받는다.