2011-09-02 55 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> 

這不會使分別驗證所述兩個對象,不可能的。

相關問題