开发者

How to pass two objects to the same Spring Controller Form submission?

I have the following pojo:

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

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

    .... getters and setters
    }

and the following Controller:

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

and the following form snippet:

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

I get the following error when submitting the form:

java.lang.IllegalArgumentException: argument type mismatch

If the objects are different and the pojos have different properties it works fine. Is there a way to m开发者_JAVA百科ake this work?


I just figured it out. The trick is to nest the pojos into another pojo.

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

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

use a controller like this:

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

and a form like this:

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

This does make validating the two objects separately, impossible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜