return "redirect:/요청경로";
redirect:라는 접두어를 붙이면 Spring이 자동으로 리다이렉트를 수행함.@GetMapping("ex03")
public String ex03() {
return "redirect:/sample/ex04";
}
@GetMapping("ex04")
public String ex04() {
return "ex04";
}
/sample/ex03으로 접근함redirect:/sample/ex04로 리다이렉트/sample/ex04로 다시 요청ex04() 메서드 실행되고 ex04.jsp로 이동함insert, update, delete
| 상황 | 이유 |
|---|---|
| 폼 전송 후 | 새로고침 시 중복 제출 방지 (PRG 패턴) |
| URL을 변경하고 싶을 때 | 사용자가 다른 주소로 이동하게 하고 싶을 때 |
| 처리 후 목록으로 돌려보낼 때 | 예: 글 작성 후 글 목록 페이지로 이동 등 |
redirect는 현재 요청을 다른 요청으로 강제로 넘길 때 사용하는 Spring의 리디렉션 기능이다!
RedirectAttributes 개념redirect:/... 시, 파라미터를 URL에 자동 추가해주는 도구?key=value 형태로 쿼리스트링을 만들어줌@GetMapping("ex03")
public String ex03(RedirectAttributes rttr) {
rttr.addAttribute("name", "bbb"); // → ?name=bbb
rttr.addAttribute("age", 40); // → &age=40
return "redirect:/sample/ex04";
}
→ 결과 URL: /sample/ex04?name=bbb&age=40
@GetMapping("ex04")
public String ex04(SampleDto dto, @ModelAttribute("page") int page)
SampleDto(name=bbb, age=40) ← 이렇게 자동으로 값이 들어감@ModelAttribute 사용 이유@ModelAttribute("page")는 view에서도 사용할 수 있게 model에 넣어주는 것${page}로 꺼낼 수 있음<p>페이지 번호: ${page}</p>
| 개념 | 설명 |
|---|---|
RedirectAttributes | 리다이렉트할 때 파라미터를 쿼리스트링으로 넘길 수 있게 도와줌 |
| DTO 자동 바인딩 | URL 파라미터 이름이 DTO 필드와 일치하면 자동 객체화 |
@ModelAttribute | 단순 파라미터도 view에서 사용할 수 있게 모델에 넣어줌 |
| 리다이렉트 시 데이터 전달 | addAttribute()로 쿼리 파라미터 전달 → |
커맨드 객체나 @RequestParam/@ModelAttribute로 받기 |
RedirectAttributes.addAttribute() → URL 파라미터 전달 (ex. ?name=bbb)"name"이라는 소문자 파라미터는 SampleDto의 private String name; 필드에 바인딩됨Name=bbb처럼 대문자로 작성되면 바인딩이 안 될 수 있음 → 대소문자 일치 중요@ModelAttribute("page")와 같은 명시적 바인딩은 key 이름과 URL 파라미터가 일치해야 한다./sample/ex04?page=3 있어야 page에 값이 들어감@ModelAttribute 활용