繁体   English   中英

如何将两个对象传递给同一Spring Controller Form提交?

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

我有以下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
    }

和以下控制器:

@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

如果对象不同并且pojo具有不同的属性,则可以正常工作。 有没有办法使这项工作?

我只是想通了。 诀窍是将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>

这确实使分别验证两个对象成为不可能。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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