Note that there are some explanatory texts on larger screens.

plurals
  1. POSpringMVC controller: how to stay on page if form validation error occurs
    primarykey
    data
    text
    <p>I have next working code in my <em>SpringMVC</em> controller:</p> <pre><code>@RequestMapping(value = "/register", method = RequestMethod.GET) public void registerForm(Model model) { model.addAttribute("registerInfo", new UserRegistrationForm()); } @RequestMapping(value = "/reg", method = RequestMethod.POST) public String create( @Valid @ModelAttribute("registerInfo") UserRegistrationForm userRegistrationForm, BindingResult result) { if (result.hasErrors()) { return "register"; } userService.addUser(userRegistrationForm); return "redirect:/"; } </code></pre> <p>In short <code>create</code> method try to validate <code>UserRegistrationForm</code>. If form has errors, it leaves user on the same page with filled form fields where error message will be shown.</p> <p>Now I need to apply the same behaviour to another page, but here I have a problem:</p> <pre><code>@RequestMapping(value = "/buy/{buyId}", method = RequestMethod.GET) public String buyGet(HttpServletRequest request, Model model, @PathVariable long buyId) { model.addAttribute("buyForm", new BuyForm()); return "/buy"; } @RequestMapping(value = "/buy/{buyId}", method = RequestMethod.POST) public String buyPost(@PathVariable long buyId, @Valid @ModelAttribute("buyForm") BuyForm buyForm, BindingResult result) { if (result.hasErrors()) { return "/buy/" + buyId; } buyForm.setId(buyId); buyService.buy(buyForm); return "redirect:/show/" + buyId; } </code></pre> <p>I faced with issue of dynamic url. Now if form has errors I should specify the same page template to stay on current page, but also I should pass <code>buyId</code> as a path variable. Where are a conflict in this two requirements. If I leave this code as is, I get an error (I'm using <em>Thymeleaf</em> as a template processor):</p> <pre><code>Error resolving template "/buy/3", template might not exist or might not be accessible by any of the configured Template Resolvers </code></pre> <p>I can write something like <code>return "redirect:/buy/" + buyId</code>, but in this case I lose all data and errors of form object.</p> <p>What should I do to implement in <code>buyPost</code> method the same behaviour as in <code>create</code> method?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload