【问题标题】:Spring bind data from JSP to ControllerSpring将数据从JSP绑定到Controller
【发布时间】:2015-11-07 06:13:00
【问题描述】:

我有一个register.jsp 页面,我将以下数据绑定到一个modelAttribute userform

<form:form method="post" modelAttribute="userform"
    enctype="multipart/form-data" autocomplete="off" class="form">

    <spring:bind path="firstName">
        <label>First Name: </label>
        <form:input path="firstName" placeholder="First Name" />
    </spring:bind>

    <spring:bind path="lastName">
        <label class="control-label">Last Name: </label>
        <form:input path="lastName" placeholder="Last Name" />
    </spring:bind>
</form:form>

控制器上的 get 和 post 方法在哪里:

@RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register(@ModelAttribute("userform") Employee employee, Model model) {
        List<Role> roleList = roleService.getAllList();
        model.addAttribute("roleList", roleList);
        model.addAttribute("userform", employee);
        return "employee/register";
    }

    @RequestMapping(value = { "/register" }, method = RequestMethod.POST)
    public String processRegistration(@Valid @ModelAttribute("userform") Employee employee, BindingResult result,
            Model model, HttpServletRequest request) throws IllegalStateException, IOException  {



        //(expecting the data from jsp) nothing in the employeee object :(
        //dosomething

        return "employee/register";
    }

虽然我使用了相同的名称userform,并且实体Employee 上的属性名称完全相同,但我无法将表单数据从JSP 获取到Controller。我一定在这里做错了,但找不到。任何帮助将不胜感激。

【问题讨论】:

  • 你用的是什么版本的spring??

标签: java spring jsp spring-mvc


【解决方案1】:

我自己想出了答案。

由于我在我的 JSP 表单中使用了enctype="multipart/form-data",它需要在servlet-context.xml 中配置一个名为“CommonsMultipartResolver”的 bean。整个bean可以写成

<beans:bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

【讨论】:

    【解决方案2】:

    除了@Ralph 回答我想解释为什么你需要从你的jsp 中删除以下行

    <spring:bind path="firstName">
    <spring:bind path="lastName">
    

    根据此链接上给出的答案Difference between spring:bind and form:form

    当您使用 &lt;form:form&gt; 时,没有必要使用 &lt;spring:bind&gt;,因为两者在模型属性方面的作用相同。

    这里&lt;form:form&gt; 也生成HTML 表单标记,而&lt;spring:bind&gt; 你需要自己编写标记。

    您还应该知道 sping 如何处理域对象的绑定,正如@Ralph 在他的回答中提到的那样,您需要使用 form backing object 并修改您的方法,如下所示

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register(Employee employee, Model model) {
    
    }
    

    Q- 上面的代码发生了什么?

    A- 当 Spring MVC 发现域对象作为方法参数存在时,Spring MVC 会自动引入一个实例,对于域对象,该实例与 由新关键字如下所示

    Employee emp=new Employee();
    

    Employee 域对象的属性通常未初始化,接受与 URL 查询字符串中可用的 Employee 对象属性同名的任何参数。 Spring MVC 使用 Java 反射来区分域对象的属性名称。

    欲了解更多信息,请访问Binding and Validation of Handler Parameters in Spring MVC Controllers

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-15
      • 1970-01-01
      相关资源
      最近更新 更多