세션을 사용해서 여러 폼에 걸쳐 데이터를 나눠 입력 받고 저장하기
완료된 경우에 세션에서 모델 객체 제거하기
@Controller
@SessionAttributes("event")
public class SampleController {
@GetMapping("/events/form/name")
public String eventsFormName(Model model) {
model.addAttribute("event", new Event());
// 자동으로 세션에 넣어줌
return "events/form-name";
}
@PostMapping("/events/form/name")
public String eventsFormNameSubmit(@ModelAttribute @Valid Event event, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "/events/form-name";
}
return "redirect:/events/form/limit";
}
@GetMapping("/events/form/limit")
public String eventsFormLimit(@ModelAttribute @Valid Event event, Model model) {
model.addAttribute("event", event);
// 자동으로 세션에 넣어줌
return "events/form-limit";
}
@PostMapping("/events/form/limit")
public String eventsFormLimitSubmit(@ModelAttribute @Valid Event event, BindingResult bindingResult, SessionStatus sessionStatus){
if(bindingResult.hasErrors()){
return "/events/form-limit";
}
sessionStatus.setComplete();
// 데이터베이스에서 save 했다고 가정
return "redirect:/events/list";
}
@GetMapping("/events/list")
public String getEvents(Model model){
Event event = new Event();
event.setName("spring");
event.setLimit(10);
// 데이터베이스에서 읽어왔다고 가정한다.
List<Event> eventList = new ArrayList<>();
eventList.add(event);
model.addAttribute("eventList", eventList);
return "/events/list";
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="#" th:action="@{/events/form/name}" method="post" th:object="${event}">
<p th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Incorrect date</p>
Name : <input type="text" title="name" th:field="*{name}"/>
<input type="submit" value="Create"/>
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="#" th:action="@{/events/form/limit}" method="post" th:object="${event}">
<p th:if="${#fields.hasErrors('limit')}" th:errors="*{limit}">Incorrect date</p>
Limit : <input type="text" title="limit" th:field="*{limit}"/>
<input type="submit" value="Create"/>
</form>
</body>
</html>
참고