gpt4 book ai didi

java - Spring 支架 Controller : how to selectively switch off validation

转载 作者:太空宇宙 更新时间:2023-11-04 12:06:34 25 4
gpt4 key购买 nike

在我的 Controller 中,我有一个创建实体的方法

import javax.validation.Valid;
...
@RestController
public class Controller {

@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<?> create(@Valid @RequestBody RequestDTO requestDTO) {
...

import org.hibernate.validator.constraints.NotEmpty;
...
public class RequestDTO
@NotEmpty // (1)
private String field1;
//other fields, getters and setters.

我想添加一个 Controller 方法

update(@Valid @RequestBody RequestDTO requestDTO)

但在此方法中,应允许 field1 为空或 null,即该行

@NotEmpty // (1)

RequestDTO 应被忽略。

我该怎么做?我是否必须编写一个与 RequestDTO 完全相同但没有注释的类?或者是否可以通过继承来实现?

最佳答案

简短回答:使用验证组:

@NotEmpty(groups = SomeCriteria.class)
private String field1;

并在方法处理程序参数中引用您想要的组:

public ResponseEntity<?> create(@Validated(SomeCriteria.class) @RequestBody RequestDTO requestDTO)

在上面的示例中,将应用 SomeCriteria 组中的验证,而其他组将被忽略。通常,这些验证组被定义为空接口(interface):

public interface SomeCriteria {}

您可以在Hibernate Validator documentation中阅读有关这些组约束的更多信息。 .

关于java - Spring 支架 Controller : how to selectively switch off validation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40296953/

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