Spring将数据从JSP绑定到Controller

时间:2015-11-07 06:13:00

标签: java spring jsp spring-mvc

我有一个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。我必须在这里做错事但却找不到。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

我自己想出了答案。

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

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

答案 1 :(得分:0)

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

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

根据此链接提供的答案Difference between spring:bind and form:form

使用<spring:bind>时不必使用<form:form>,因为两者在模型属性方面都做同样的事情。

此处<form:form>也会生成HTML表单标记,而使用<spring:bind>则需要自己编写标记。

另外你应该知道sping如何处理Domain Object的绑定,正如@Ralph在他的回答中提到你需要使用表单支持对象并修改你的方法如下

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

}

问:上述代码中发生了什么?

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