2015-11-07 65 views
0

我有一个register.jsp页面,其中我将以下数据绑定到modelAttribute userformSpring将数据从JSP绑定到控制器

<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> 

哪里得到和控制器上岗位的方法是:

@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形成到控制器。我一定在这里做错了事,但找不到它。任何帮助,将不胜感激。

+0

什么版本的春天你使用? – Dev

+0

@Dev 4.1.6.Release – Sujan

回答

1

我想通了自己的答案。

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

<beans:bean id="multipartResolver" 
     class="org.springframework.web.multipart.commons.CommonsMultipartResolver" /> 
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>你需要自己写标记。

你也应该知道如何处理蔓延扩散域对象的结合,正如@Ralph在他的回答提到你需要使用表单支持对象并修改方法如下图所示

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

} 

Q-什么是在上面的代码中发生?

A-春MVC发现域对象存在作为实例由Spring MVC的自动导入方法的参数,对于域对象该实例为与由新的关键字像下面创建实例

Employee emp=new Employee(); 

雇员域对象的属性通常是未初始化的接受URL查询S研与相同名称的任何参数为可用雇员对象属性NG。 Spring MVC使用Java反射消除域对象属性的名称。

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

相关问题