개발공부/Spring

[Spring] Redirect

jnnjnn 2024. 4. 18. 17:46

 

Redirect란?

사용자가 처음 요청한 URL이 아닌, 다른 URL로 보내는 것을 말한다

 

Spring에서 컨트롤러의 리턴값에 redirect: 키워드를 붙이면 3xx번대의 HTTP redirection 응답을 받았을 때 Location 헤더에 있는 값으로 다시 요청을 보낸다

@GetMapping("sub2")
public String sub2() {
	// 리다이렉션 시 main22/sub1로 이동
    return "redirect:/main22/sub1";
}

 

 

RedirectAttributes

리다이렉트시 사용자가 기존에 요청했던 데이터는 사라진다. 따라서 리다이렉트가 되어도 데이터가 유지되려면 RedirectAttributes의 인스턴스에 데이터를 저장해주어야 한다

 

addAttribute

쿼리스트링을 통해 데이터가 전달된다

@GetMapping("sub11")
public String method11(RedirectAttributes rttr) {
    // redirection 시 정보 전달은 RedirectionAttributes 활용
    // addAttribute : 쿼리스트링에 붙음
    rttr.addAttribute("type", "soccer");

	// 리다이렉션 시 main22/sub12 호출
    return "redirect:/main22/sub12";
}

 

addFlashAttribute

데이터가 모델을 통해 전달된다

@GetMapping("sub11")
public String method11(RedirectAttributes rttr) {

// addFlashAttribute : 모델에 붙음
    rttr.addFlashAttribute("attr1", List.of("car", "fodd", "phone"));

	// 리다이렉션 시 main22/sub12 호출
    return "redirect:/main22/sub12";
}

 

 

 

redirect 사용예제

로그인 성공 시 로그인 성공 페이지로, 실패 시 다시 로그인폼 페이지로 리다이렉트되는 예제이다

RedirectAttributes로 값을 전달해 리다이렉트가 발생해도 데이터가 사라지지 않는다

   @GetMapping("sub3")
    public void sub3() {
        // login form 있는 jsp (view)로 forward
    }

    @PostMapping("sub4")
    public String method4(String id, String password, RedirectAttributes rttr) {
        // 아이디와 비밀번호가 같으면 로그인 성공
        boolean ok = id.equals(password);
		
        // 로그인 성공 시
        // 성공 후 보여주는 페이지로 이동   
        if (ok) {
            rttr.addAttribute("type", "login");

            return "redirect:/main22/sub5";
        } else {
            // 로그인 실패 시
            // 로그인 form 있는 페이지로 이동

            rttr.addAttribute("type", "fail");
            return "redirect:/main22/sub3";
        }
    }
<%-- sub3 --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="jakarta.tags.core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%-- 로그인 실패시 출력 --&>
<c:if test="${param.type eq 'fail'}">
    <div style="padding: 20px; background-color: pink">
        아이디와 패스워드를 확인하세요
    </div>
</c:if>

<form action="/main22/sub4" method="post">
    <div>
        id
        <input type="text" name="id">
    </div>
    <div>
        pw
        <input type="text" name="password">
    </div>
    <div>
        <input type="submit" value="로그인">
    </div>
</form>
</body>
</html>
<%-- sub5.jsp --%>
<h3>로그인 성공</h3>