Spring MVC和JSR

编程入门 行业动态 更新时间:2024-10-25 13:24:27
本文介绍了Spring MVC和JSR-303 hibernate条件验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个我要验证的表单。它包含2个地址变量。 address1必须经过验证,address2必须根据某些条件进行验证

I've a form I want to validate. It contains 2 Address variables. address1 has always to be validated, address2 has to be validated based on some conditions

public class MyForm { String name; @Valid Address address1; Address address2; } public class Address { @NotEmpty private String street; }

我的控制器会自动验证并绑定我的表单obj

my controller automatically validates and binds my form obj

@RequestMapping(...) public ModelAndView edit( @ModelAttribute("form") @Valid MyForm form, BindingResult bindingResult, ...) if(someCondition) { VALIDATE form.address2 USING JSR 303

问题是如果我使用LocalValidatorFactoryBean验证器,我就无法重用Spring提供的BinidingResult对象。绑定不起作用,因为'result'的目标对象是'MyForm'而不是'Address'

the problem is that if I use the LocalValidatorFactoryBean validator i can't reuse the BinidingResult object provided by Spring. The bind won't work as the target object of 'result' is 'MyForm' and not 'Address'

validate(form.getAddress2(), bindingResult) //won't work

我想知道什么是标准/干净的方法来进行条件验证。

I'm wondering what's the standard/clean approach to do conditional validation.

我正在考虑以编程方式在我的控制器中创建一个新的BindingResult。

I was thinking in programmatically create a new BindingResult in my controller.

final BindingResult bindingResultAddress2 = new BeanPropertyBindingResult(address2, "form"); validate(form.getAddress2(), bindingResultAddress2);

但是我从bindingResultAddress2获得的错误列表无法添加到一般的'bindingResult'中因为字段名称不正确('street'而不是'address2.street')并且绑定不起作用。

but then the List of errors I obtain from bindingResultAddress2 can't be added to the general 'bindingResult' as the field names are not correct ('street' instead of 'address2.street') and the binding won't work.

一些脏方法是扩展BeanPropertyBindingResult接受一些字符串附加到字段名称..你有更好的方法吗?

Some dirty approach would be to extend BeanPropertyBindingResult to accept some string to append to the fields name.. do you have a better approach?

推荐答案

验证分层的标准方法结构是使用 pushNestedPath() / popNestedPath(),虽然我不确定它如何与JSR-一起使用303:

The standard approach for validating hierarchical structures is to use pushNestedPath()/popNestedPath(), though I'm not sure how it plays with JSR-303:

bindingResult.pushNestedPath("address2"); validate(form.getAddress2(), bindingResult); bindingResult.popNestedPath();

更多推荐

Spring MVC和JSR

本文发布于:2023-10-07 17:28:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1470026.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Spring   MVC   JSR

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!