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?
try adding @SessionAttributes for the model attribute on top of the controller and remove the session attribute when done
@SessionAttributes("reservation")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.