how to get form values to controller in spring mvc

laxmi picture laxmi · May 31, 2017 · Viewed 13k times · Source

I am trying to get form values from jsp to controller in spring mvc, but i am not able to get form data.

This is my DTO (bean)

public class LoginDTO implements Serializable {

private Long id;
private String username;
private String password;
// setter and getter methods
}

and my Jsp

<form class="form-signin" action="test" method="get" modelAttribute="userFormData">
     <input type="text" class="form-control" 
           placeholder="Email" required autofocus>

     <input type="password" class="form-control" 
           placeholder="Password" required>

     <input class="btn btn-md btn-success btn-block" 
           type="submit" value="Signin">
</form>

and my controller

@RequestMapping(value = "/test", method = RequestMethod.GET)
public String checkLogin(@ModelAttribute("userFormData") LoginDTO formData, BindingResult 
result) {

    System.out.println("Controller...");

    System.out.println("=====>  " + formData.getUsername());
    System.out.println("=====>  " + formData.getPassword());

}

Answer

StanislavL picture StanislavL · Jun 1, 2017

Add names to the controls on your JSP pages.

<input type="text" name="username" ...>
<input type="password" name="password" ...>

To let spring understand which form control value should go to which property of the LoginDTO