2

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());

}
Edgard Leal
  • 2,592
  • 26
  • 30
laxmi
  • 83
  • 2
  • 3
  • 10

3 Answers3

3

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

StanislavL
  • 56,971
  • 9
  • 68
  • 98
1

we can also use the springframework has given us a form tags.so that we can also use that but in that case you have to define your the input path same as the member varibale given in your class.

like this

<form:form method="post" modelAttribute="userFormData">
    <form:input path="username" />
    <form:input path="password" />

Then in the controller you can write like this as you have written

public String checkLogin(@ModelAttribute("userFormData") LoginDTO formData, BindingResult 
result)
ayushs27
  • 97
  • 1
  • 8
0

In case you want to get the result on other jsp page as well as on console then do:

public String checkLogin(@ModelAttribute("userFormData") LoginDTO formData, BindingResult 
result , Model model){
    System.out.println("=====>  " + formData.getUsername()); //this outputs username on console
    System.out.println("=====>  " + formData.getPassword()); //this outputs password on console
    model.addAttribute("LoginDTO ", LoginDTO );
    return "success"; //this is the return page where the username and password will be rendered as view
}
Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55