spring-guides / gs-validating-form-input

Validating Form Input :: Learn how to perform form validation with Spring.

Home Page:http://spring.io/guides/gs/validating-form-input/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to do this if the url contains a parameter?

wimdeblauwe opened this issue · comments

How do I make this work with a path variable? Suppose the URL is /user/123 for example.

The controller would have something like

@PostMapping("/user/{userId}")
public String updateUser(@PathVariable("userId") long id, @Valid PersonForm personForm, BindingResult bindingResult) {
  if (bindingResult.hasErrors()) {
            return "form";
        }

        return "redirect:/user/{userId}";
}

I tested this and the redirect in the success case works, but the error case seems to work at first, but if you then update the form again and submit again, it does not go through the same controller method. So how to make this work?

Not sure I follow the bit about "does not go through the same controller". If you POST to the same endpoint, it has no choice but to do so, I should think. Maybe you could fork the project and push a change to your fork so we can see what you mean?

Hi,

I created a fork of the project to better explain what I mean.

You can find the changes here: wimdeblauwe@b567f27

You can check out the branch pathvariable-example from https://github.com/wimdeblauwe/gs-validating-form-input to test it.

This is what happens:

  1. I open the url http://localhost:8080/user/123 in my browser. This gives me an empty form.
  2. I press on 'Submit'. This shows the validation messages as expected. If I type something invalid, the form data is retained. The url stays at http://localhost:8080/user/123
  3. Press 'Submit' again with invalid data. The url jumps to http://localhost:8080/user/0 suddenly.

In my actual application, the url jumps to http://localhost:8080/user/, but that might be because I use objects as the path variable and not a long.

I would appreciate you having a look to the changes and let me know if I am doing something wrong or if there is maybe a bug somewhere?

There is also a question on this on SO (http://stackoverflow.com/questions/18137326/springmvc-controller-how-to-stay-on-page-if-form-validation-error-occurs) I found, but I think the answers could be better.

In your @GetMapping you set the "id" property on the form object, but in the @PostMapping you don't. I think that's all there is to it.

But then why does it work the first time I submit? Why does the url stay correct there?

Because that was the URL that you submitted the form to. But the id is 0, so the HTML is different the second time you see that form, and it submits to the wrong URL on the third visit.

ok. Works if I set the path variable on the form object in case the validation fails. Thx for helping me out!