Post/Redirect/Get : redirect를 사용해야하는 이유

2024. 1. 4. 10:49
728x90

Post 요청 후 return이 다시 그 입력받은 html 페이지로 설정되어 있으면 

    @GetMapping("/create-view")
    public String createView() {
        return "create";
    }
    
	@PostMapping("/create")
    public String create(@RequestParam("name") String name,
                         @RequestParam("email") String email
                         ) {
        StudentDto student = service.createStudent(name, email);
        log.info(student.toString());
        return "create";
    }

새로고침을 하면 

이러한 알림창이 뜬다. 

 

>> 이 알림은 사용자가 처음 GET 요청을 받은 HTML 페이지가 아니라,

Form의 POST에 대한 응답이기 때문에... > 새로고침을 할 경우에 전송되었던 Form이 다시 전달되므로 

새로고침 할 때마다 계속 똑같은 데이터가 들어오게 된다... 

이런 현상을 Double Post Problem이라고 한다.

 

- Post/Redirect/Get 패턴

이를 해결하기 위해 > POST 요청을 통해 데이터를 전송한 경우

다른 url로 이동하도록 한다!!!! 

    @PostMapping("/create")
    public String create(@RequestParam("name") String name,
                         @RequestParam("email") String email
                         ) {
        StudentDto student = service.createStudent(name, email);
        log.info(student.toString());

        //궁극적으로 html 을 반환하지 않도록 해야 한다....
        // 다시 create-view로 이동하게끔!!!
        return "redirect:/create-view";

 

>> 이렇게 redirect:/로 원래 폼을 요청했던 url로 이동하도록 하면 된다! 

그러면 새로고침을 해도 다시 /create url로 가서 폼 요청을 하기 때문에 아무 문제 없다~!!!

 

 

 

 

728x90

'Programming > Spring, SpringBoot' 카테고리의 다른 글

Spring Data JPA (Java Persistence API)  (2) 2024.01.07
MyBatis  (1) 2024.01.04
Spring MVC & Thymeleaf  (4) 2024.01.03
스프링부트 기초  (0) 2024.01.03
Spring 어노테이션 정리  (0) 2023.12.29

BELATED ARTICLES

more