2011-09-02 77 views
2

我有以下POJO:如何将两个对象传递给同一个Spring Controller表单提交?

public class Foo { 
    @Size(min=0,max=10) 
    private String bar = null; 

    @Size(min=0,max=10) 
    private String baz = null; 

    .... getters and setters 
    } 

及以下控制器:

@Controller 
@RequestMapping(value = "/path", method = RequestMethod.POST) 
public class Control { 
    public String handler(@Valid Foo foo1, BindingResult res_foo1, @Valid Foo foo2, BindingResult res_foo2){ 
      //Business logic 
     } 
    } 

和下面的表单代码:

<form action="/path"> 
    <input name="foo1.bar" type="text" /> 
    <input name="foo1.baz" type="text" /> 
    <input name="foo2.bar" type="text" /> 
    <input name="foo2.baz" type="text" /> 
</form> 

提交表单时,我得到了以下错误:

java.lang.IllegalArgumentException: argument type mismatch 

如果对象不同,pojos具有不同的属性,它可以正常工作。有没有办法做到这一点?

回答

6

我只是想通了。诀窍是将pojos嵌入另一个pojo。

public class Nest { 
    @Valid 
    private Foo one = null; 

    @Valid 
    private Foo two = null; 
    .... getters and setters 
} 

使用的控制器是这样的:

@Controller 
@RequestMapping(value = "/path", method = RequestMethod.POST) 
public class Control { 
    public String handler(@Valid Nest nest, BindingResult res_nest){ 
      //Business logic 
    } 
} 

和像这样的形式:

<form action="/path"> 
    <input name="one.bar" type="text" /> 
    <input name="one.baz" type="text" /> 
    <input name="two.bar" type="text" /> 
    <input name="two.baz" type="text" /> 
</form> 

这不会使分别验证所述两个对象,不可能的。

相关问题