springformsspring-bootrequestsubmission

Spring not reading model attributes from form submission


In my current spring-boot project, I have this form:

<form class="form-container" id="form" method="post" th:object="${command}" th:action="@{/usuario/register}">
...
      <div class="form-row">
        <div class="col-25">
          <label for="login">Login</label>
        </div>
        <div class="col-75">
          <input type="text" id="login" th:field="*{username}" placeholder="Login">
        </div>
      </div>
...
</form>

which is handled by this spring controller:

  @RequestMapping(value = "/register", method=RequestMethod.POST)
  @ResponseBody
  public void doRegister(@Valid Usuario object, BindingResult result) throws Exception {
    this.serv.register(object);
  }

my problem is that object is getting a null value, not allowing the program to persist the data. Displaying the content for both variables object and result, they show null; but if I try display the parameter's value with:

System.out.println("result.model.username: "+result.getModel().get("username"));

the correct value is shown. What's the issue here, why @Valid Usuario object, BindingResult result get me a null value, but HttpServletRequest gets the correct values?

UPDATE

Based on the sugestion below, I try this:

  @ModelAttribute(value = "usuario")
  public Usuario newEntity()
  {
      return new Usuario();
  }

  @RequestMapping(value = "/register", method=RequestMethod.GET)
  public String formRegister(Model model) {
    model.addAttribute("command", newEntity());
    return "register";
  }

  @RequestMapping(value = "/register", method=RequestMethod.POST)
  @ResponseBody
  public void doRegister(@ModelAttribute("usuario") Usuario object) throws Exception {
    this.serv.register(object);
  }

But got the same problem.


Solution

  • I managed to solve this issue changing the parameter:

    @ModelAttribute("usuario") Usuario object
    

    to:

    @ModelAttribute("command") Usuario object
    

    following the suggestion in the comment above (from M.Deinum)