springformsspring-bootform-submitmodelattribute

Getting Null Value from Form Submission


In my current project, I am trying implementing a user registration form, but every time I try submit the user data to the server, the model object is staying with null value.

that's my form:

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

  <div class="form-row">
    <div class="col-75">
      <input type="password" th:field="*{password}" placeholder="Senha"/>
    </div>
  </div>

  <div class="form-row">
    <div class="col-75">
      <input type="text" th:field="*{firstName}" placeholder="Nome"/>
    </div>
  </div>

  <div class="form-row">
    <div class="col-75">
      <input type="text" th:field="*{lastName}" placeholder="Sobrenome"/>
    </div>
  </div>

  <div class="form-row">
    <div class="col-75">
      <input type="email" th:field="*{email}" placeholder="E-mail"/>
    </div>
  </div>

  <div class="form-row">
    <div class="col-75">
      <button type="button" class="button" onclick="register();">Cadastre-se</button>
    </div>
  </div>

  <div class="alert-ok" id="ok" style="display: none;">
    <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>
    <strong>Sucesso!</strong> Cadastro realizado com sucesso.
  </div>

  <div class="alert-error" id="error" style="display: none;">
    <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span>
    <strong>Erro!</strong> Não foi possivel realizar o cadastro.
  </div>
</form>

in the controller I have:

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

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

(I also tried: doRegister(@Valid Usuario object, BindingResult result) but doesn't work either - same problem)

In my service class, I got this code:

  public void register(Usuario novo) throws Exception {
    novo.setEnabled(true);
    novo.setLocked(false);
    novo.setCredenciais(new HashSet<Credencial>());
    Credencial credencial = credencialDao.findBy("nome", "web");
    novo.getCredenciais().add(credencial);
    this.dao.insert(novo);
  }

my model class:

@Entity
public class Usuario extends Model implements UserDetails {
  @Id
  @GeneratedValue(strategy=GenerationType.IDENTITY)
  private Integer id;

  @Column
  private String username;

  @Column
  private String password;

  @Column
  private String firstName;

  @Column
  private String lastName;

  @Column
  private String email;

  @OneToMany(fetch = FetchType.EAGER)
  private Set<org.loja.model.credencial.Credencial> credenciais;

  @Column
  private Date dataExpiracao;

  @Column
  private Boolean enabled;

  @Column
  private Boolean locked;

  @OneToOne(fetch = FetchType.EAGER)
  private org.loja.model.cesta.Cesta cesta;

  @OneToMany(fetch = FetchType.EAGER, mappedBy = "usuario")
  private Set<org.loja.model.pedido.Pedido> pedidos;
}

Anyone can see what's wrong here? I am stuck several hours with this problem, but cannot understand what's causing this issue. I think the code looks very similar with other codes I searched on the web handling the same operation.

update

function register() {
  var formData = new FormData(document.getElementById("form"));
  var url = document.getElementById("form").action;

  var xhr = new XMLHttpRequest();
  xhr.open("POST", url);
  xhr.onload = function(event) {
    event.preventDefault();
    var result = this.responseText;
    if(result == "")
      document.getElementById("ok").style.display = 'block';
    else
      document.getElementById("error").style.display = 'block';
  };
  xhr.send(formData);
}

Solution

  • I managed to solve this changing the parameter:

    @ModelAttribute("usuario") Usuario object
    

    to:

    @ModelAttribute("command") Usuario object
    

    in a way making the name for ModelAttribute the same of the used in the method public String formRegister(Model model).