【问题标题】:how to get form values to controller in spring mvc如何在spring mvc中获取表单值到控制器
【发布时间】:2017-11-01 16:10:08
【问题描述】:

我试图在 spring mvc 中从 jsp 获取表单值到控制器,但我无法获取表单数据。

这是我的 DTO(bean)

public class LoginDTO implements Serializable {

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

和我的 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>

和我的控制器

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

}

【问题讨论】:

    标签: spring jsp spring-mvc modelattribute


    【解决方案1】:

    为您的 JSP 页面上的控件添加名称。

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

    让spring明白哪个表单控件值应该去LoginDTO的哪个属性

    【讨论】:

      【解决方案2】:

      我们也可以使用 springframework 给我们一个表单标签。所以我们也可以使用它,但在这种情况下,你必须定义你的输入路径与你的类中给出的成员变量相同。

      喜欢这个

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

      然后在控制器中你可以像你写的那样写

      public String checkLogin(@ModelAttribute("userFormData") LoginDTO formData, BindingResult 
      result)
      

      【讨论】:

        【解决方案3】:

        如果您想在其他 jsp 页面以及控制台上获取结果,请执行以下操作:

        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
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-21
          • 2017-12-02
          • 2015-01-11
          • 2013-04-18
          • 2015-01-04
          • 1970-01-01
          • 2014-03-05
          • 1970-01-01
          相关资源
          最近更新 更多