In ReservationController.java I have the following method, which gets a reservation object from new-reservation.jsp
@PostMapping("/addBookToReservation")
public String addBookToReservation(Model model,
@Valid @ModelAttribute("reservation") Reservation reservation,
BindingResult result,
RedirectAttributes redirectAttributes) {
if(result.hasErrors()) {
return "reservation/new-reservation";
}
redirectAttributes.addFlashAttribute("reservation", reservation);
return "redirect:/book/add-book";
}
and sends it to BookController.java, where another method adds another attribute to the model
@GetMapping("/book/add-book")
public String showAddBookForm(Model model) {
model.addAttribute("book", new Book());
Reservation reservation = (Reservation) model.getAttribute("reservation");
System.out.println(reservation); //prints the object I passed it!
return "/book/add-book";
}
and returns the following add-book.jsp
<form:form action="/addBook" modelAttribute="book" method="post">
<div>
<div>
<form:label path="title">Title</form:label>
<form:input type="text" id="title" path="title" />
<form:errors path="title" />
</div>
...
</div>
<div>
<input type="submit" value="Add book">
</div>
</form:form>
Now, when I handle the form's action addBook
@PostMapping("/addBook")
public String addBook(@Valid @ModelAttribute Book book,
BindingResult result,
Model model) {
if (result.hasErrors()) {
return "book/add-book";
}
Reservation reservation = (Reservation) model.getAttribute("reservation");
System.out.println(reservation); // reservation is null!!
return "somewhere/else";
}
and I try to retrieve the reservation object from the model I get a null. How can I pass my reservation object through the JSPs I've showed you before?
EDIT-SOLVED:
I was able to solve my problem by adding @SessionAttributes("reservation")
on top of the ReservationController.java class definition and removing it once finished (following the instructions in the answer linked).
CodePudding user response:
try adding @SessionAttributes for the model attribute on top of the controller and remove the session attribute when done
@SessionAttributes("reservation")