【问题标题】:How to pass two objects to the same Spring Controller Form submission?如何将两个对象传递给同一个 Spring Controller 表单提交?
【发布时间】:2023-03-23 05:35:02
【问题描述】:

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

和下面的形式sn-p:

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

【问题讨论】:

    标签: java spring spring-mvc


    【解决方案1】:

    我刚刚想通了。诀窍是将 pojo 嵌套到另一个 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>
    

    这确实使得无法单独验证两个对象。

    【讨论】:

      猜你喜欢
      • 2020-11-02
      • 2018-02-01
      • 1970-01-01
      • 2016-12-20
      • 1970-01-01
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 2010-09-07
      相关资源
      最近更新 更多