Mohd Erwin
Mohd Erwin

Reputation: 33

@ModelAttribute populate form field from request param instead of backing form

My problem is: @ModelAttribute populate form field from request param instead of form DTO if request param and form field has same name.

Example: I have form with input filed called name:

<input type="text" name="name" />

Given form with value name=John,
If I submit form (web method POST) using url: http://localhost:8080/user/?name=Michael
I will have query param and form field that has same name.
What I expect is: name field should be populated from Form Field, not query params.

MyForm.java

public class MyForm {
    private String name;
    private Boolean isMale;
    private Byte status;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Boolean getIsMale() {
        return isMale;
    }
    public void setIsMale(Boolean isMale) {
        this.isMale = isMale;
    }
    public Byte getStatus() {
        return status;
    }
    public void setStatus(Byte status) {
        this.status = status;
    }
}

MyController.java

@Controller
@RequestMapping("/user")
public class UserController {
  @RequestMapping(value = "/", method = RequestMethod.POST)
  public String index(
        Model model,
        @ModelAttribute("form") MyForm form,
        BindingResult bindingResult) {
    String name = form.getName(); //this contains value from form: Michael
    Boolean isMale = form.getIsMale(); //this contains value from query parameter: true
    Byte status= form.getStatus(); //this contains value from form: 1
    return "views/index";
}

When I submit the form with values:

name = Michael
isMale = false
status = 1

using url with query params:

http://localhost:8080/user/?isMale=true

then isMale will contains value true, that populate from query param.

What I expects is, isMale should contains false that populate from Form Field. How to solve this problem...?

Upvotes: 1

Views: 911

Answers (1)

Daud
Daud

Reputation: 7877

You should use @RequestBody annotation instead of @ModelAttribute if you want just the request body (which contains your form data) to populate your Java object

(as a side note, its bad design to pass the same parameter name in both your query string as well as in your form data. Do refactor, if possible)

Upvotes: 1

Related Questions