개발천재

[Spring Boot] RedirectAttributes 이해하기 본문

개발 준비/Spring Boot

[Spring Boot] RedirectAttributes 이해하기

세리블리 2025. 2. 21. 21:51
반응형
RedirectAttributes는 페이지 이동할 때 잠깐 붙였다가, 한 번 보여주고 바로 버려지는 포스트잇 메모!

 

 

 

RedirectAttributes 이해하기

Spring에서 리다이렉트(다른 페이지로 이동)할 때, 데이터를 잠깐 전달하는 방법이다. redirect:/member/view처럼 리다이렉트를 하면 새로운 요청이 만들어진다. 그래서 Model이나 @RequestParam으로는 데이터를 전달할 수 없다.

이때 RedirectAttributes가 잠깐 데이터를 붙여서 보내주는 역할을 한다. 회원가입, 글 작성, 삭제 등이 성공했을 때 “성공했습니다!” 같은 알림 메시지를 다음 화면에 한 번만 보여주고 싶을 때 사용한다.

 

RedirectAttributes를 많이 쓰는 경우

  • 회원가입 후 → “회원가입 성공!” 메시지
  • 로그인 실패 → “아이디나 비밀번호가 틀렸습니다.” 메시지
  • 게시글 등록/삭제 후 → “게시글이 등록/삭제되었습니다.” 메시지
  • 비밀번호 변경 후 → “비밀번호가 변경되었습니다.” 메시지

 

Controller에서 RedirecAttributes 설정

@PostMapping("insert")
public String insert(
        MemberDto dto,
        RedirectAttributes redirectAttributes
) {
    memberService.saveMember(dto); // 회원 저장
    redirectAttributes.addFlashAttribute("msg", "신규데이터가 입력되었습니다");
    return "redirect:/member/view"; // view 페이지로 리다이렉트
}

 

View 화면에서 메세지 보여주기

<h2>회원 리스트</h2>
<th:block th:unless="${msg}==null">
  <div class="alert alert-warning alert-dismissible fade show" role="alert">
    [[ ${msg} ]]
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
  </div>
</th:block>

 

 


 

 

RedirectAttributes 옵션

addFlashAttribute()
한 번만 데이터를 전달하고 사라진다. 새로운 요청이 끝나면(페이지를 새로고침하면) 데이터가 없어진다.
사용 예시: 성공 메시지, 에러 메시지 등 임시로 보여주는 데이터

redirectAttributes.addFlashAttribute("msg", "신규 데이터가 입력되었습니다");

 

 

addAttribute()

쿼리 파라미터로 데이터를 전달한다. URL에 직접 데이터가 보인다. 페이지를 새로고침해도 계속 유지된다.
예) /member/view?id=3&msg=success
사용 예시: 조회할 ID, 검색어 등을 전달할 때

redirectAttributes.addAttribute("id", 3);
redirectAttributes.addAttribute("msg", "success");


실제 리다이렉트되는 URL:

/member/view?id=3&msg=success

 

 

addAllAttributes()
여러 데이터를 Map 형태로 한 번에 추가한다. addAttribute()와 똑같이 URL에 보인다.
사용 예시: 한꺼번에 여러 데이터를 전달할 때

Map<String, Object> map = new HashMap<>();
map.put("id", 3);
map.put("msg", "success");
redirectAttributes.addAllAttributes(map);


리다이렉트된 URL

/member/view?id=3&msg=success

 

 

mergeAttributes()
기존 Attribute에 새로운 데이터만 추가하거나, 덮어쓰기할 때 사용한다. addAttribute()와 비슷하지만, 이미 있는 데이터는 유지하고 새로운 데이터만 추가한다.
사용 예시: 기본 데이터가 있는 상태에서 추가 데이터를 넣고 싶을 때

redirectAttributes.addAttribute("id", 1);
redirectAttributes.mergeAttributes(Map.of("msg", "welcome"));



 

 

반응형