📓 TechNote/Spring

[Spring] RedirectAttributes

버터감자 2023. 3. 5. 17:27
728x90

PRG 패턴이란?

- POST방식으로 어떤 처리를 하고 Redirect하여 GET방식으로 특정한 페이지로 이동하는 패턴

 

스프링MVC에서는 PRG패턴을 위해 RedirectAttributes 타입을 제공한다. 

addAttribute( 키, 값)

- 리다이렉트할때 쿼리 스트링이 되는 값을 지정

- URL에 쿼리 스트링으로 추가된다.

 

addFlashAttribute( 키, 값 )

- 일회용으로 데이터를 전달하고 삭제되는 값을 지정

- URL에 보이지는 않지만 JSP에서 일회용으로 사용가능


✔ RedirectAttributes 예시

 

👉testcontroller

@GetMapping("/test01")
	public String test01(RedirectAttributes redirectAttributes) {
		
		redirectAttributes.addAttribute("name", "ABC");
		redirectAttributes.addFlashAttribute("result", "success");
		
		return "redirect:/test02";
		
	}
	
	@GetMapping("/test02")
	public void test02() {
		
	}

👉test02.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HI</title>
</head>
<body>
	<h1>ADD FLASH ARRTIBUTE : ${result}</h1>
</body>
</html>

 

✔ 실행결과

 

👉 addAttribute로 입력한값이 URL에 쿼리스트링으로 보여짐

 

👉 test02.jsp 실행결과 

addFlashAttribute( 키, 값 )은 일회용이므로 새로고침하면 result 변수는 존재하지 않는다.