【问题标题】:java - spring bean validation - disable specific validation on some fieldsjava - spring bean 验证 - 禁用某些字段的特定验证
【发布时间】:2018-04-19 16:12:57
【问题描述】:

我的 spring mvc 应用程序中有一个视图模型,我需要在某些字段上启用或禁用特定验证。例如,假设我有 2 个视图表单,它们将数据发送到不同的控制器方法,但两种方法都使用相同的视图模型类,如下所示:

@RequestMapping(value = "/method1", method = RequestMethod.POST)
@ResponseBody
public ViewModel method1(@RequestBody @Valid ViewModel viewModel){
      ...
}

@RequestMapping(value = "/method2", method = RequestMethod.POST)
@ResponseBody
public ViewModel method2(@RequestBody @Valid ViewModel viewModel){
    ...
}

这是我的视图模型的一部分:

private Integer test;

我需要在test 字段上使用@NotNull 注释,但只在控制器中的method2 中使用。事实上,我不需要在method1 中进行此验证。有没有办法做到这一点?

【问题讨论】:

标签: java validation spring-mvc


【解决方案1】:

我认为你的方法应该是写一个像

这样的超类
class ViewModel {
   @NotNull
   private Integer test;

   public Integer getTest() {
   }
}

class ViewModelSuper extends ViewModel {
   private Integer test;

   @Override
   public Integer getTest() {
   }
}


the you'll have 

@RequestMapping(value = "/method1", method = RequestMethod.POST)
@ResponseBody
public ViewModel method1(@RequestBody @Valid ViewModelSuper viewModel){
  ...
}

@RequestMapping(value = "/method2", method = RequestMethod.POST)
@ResponseBody
public ViewModel method2(@RequestBody @Valid ViewModel viewModel){
...
}

由于只需要对method2进行验证,因此method1使用超类

【讨论】:

    【解决方案2】:

    删除方法1中的@valid。它不会验证。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-23
      • 1970-01-01
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 2011-07-19
      相关资源
      最近更新 更多