简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM