gpt4 book ai didi

java - 如何将两个对象传递给同一个Spring Controller 表单提交?

转载 作者:行者123 更新时间:2023-11-30 05:56:22 25 4
gpt4 key购买 nike

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

@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 具有不同的属性,则可以正常工作。有办法让它工作吗?

最佳答案

我刚刚想通了。诀窍是将 pojo 嵌套到另一个 pojo 中。

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

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

使用这样的 Controller :

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

这确实使得单独验证两个对象变得不可能。

关于java - 如何将两个对象传递给同一个Spring Controller 表单提交?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7278218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com