I have the following Spring MVC controller method:
@RequestMapping(value = "/tournament/{id}/set-format", method = RequestMethod.POST)
public String processSetTournamentFormat(Model model,
@ModelAttribute("formatSettings") FormatSettings formatSettings,
@AuthenticationPrincipal UserAccount currentUser,
@PathVariable("id") int tournamentId,
RedirectAttributes redirectAttributes)
throws TournamentAccessDenied, TournamentNotFoundException, ModifyngOngoingTournamentException {
Tournament currentTournament = tournamentManagementService.findTournamentById(tournamentId);
tournamentManagementService.setTournamentFormat(currentTournament, formatSettings);
model.addAttribute("tournamentId", currentTournament.getId());
return "redirect:/tournament/{tournamentId}/setup";
}
When I click submit button in corresponding form I get an exception:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalArgumentException: Model has no value for key 'tournamentId'
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:869)
javax.servlet.http.HttpServlet.service(HttpServlet.java:644)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:316)
[...]
Everything works well when I remove redirectAttributes parameter but I need it to add flash attributes in case of any error. I try to understand why URL template doesn't work. It is also ok when (without removing redirectAttributes) I just use:
return "redirect:/tournament/" + currentTournament.getId() + "/setup";
My Spring version is 4.1.7
There's no point providing both Model and RedirectAttributes parameters in your handler method. RedirectAttributes can do everything Model can do and more.
The actual issue is the following:
ModelAndViewContainer which holds a reference to a Model. Model argument to your handler method, Spring MVC returns the default Model in the ModelAndViewContainer.RedirectAttributes argument to your handle method, Spring MVC creates a new instance and uses it to overwrite the default ModelAndViewContainer Model.Model, the ModelAndViewContainer won't have access to it and therefore neither will component that process the redirect: view name.Choose one. You don't need both.
redirectAttributes.addAttribute("tournamentId", currentTournament.getId());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With