4 回答

TA貢獻1815條經驗 獲得超10個贊
您的 DTO 類是正確的。你必須使用@Valid注釋。
例如 :
@Controller
public class Controller {
@PostMapping("/")
public String checkPersonInfo(@Valid AbstractDTO abstractDTO, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "some-page";
}
return "some-other-page";
}
}
請參閱此Spring Boot 驗證表單輸入示例以供參考。
為什么要使用@Valid注解?
這允許您驗證應用于類的數據成員的約束集。
但是,如果您的項目中有基于 XML 的配置,則必須將其添加到下面給出的applicationContext.xml中。(來源:這里)
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="webBindingInitializer">
<bean
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<property name="validator" ref="validator" />
</bean>
</property>
</bean>
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
</bean>

TA貢獻2003條經驗 獲得超2個贊
您有一個帶有某些請求正文的端點,例如;
@RestController
public class TheController {
@PostMapping(path = "/doSomething", consumes = "application/json", produces = "application/json")
public void post(@Valid @RequestBody AbstractDTO request) {
//code
}
}
您需要@Valid為請求對象添加注釋。只有這樣,您才能為端點啟用AbstractDTO驗證/doSomething。
檢查這里,了解更深入的細節

TA貢獻1825條經驗 獲得超4個贊
描述
就我而言,我定義 1 個父類 A 有 3 個子類 B、C、D,例如:
公共 A { 私有 B bCommand; 私有 C cCommand;私有D dCommand;}
我為3個子類中的一些字段注釋了@NotNull、@NotBlank。在控制器中,我為這樣的函數添加了@Valid:
@PostMapping() public ResponseEntity create(@RequestBody @Valid A
command){ }
解決方案
我為具有需要檢查約束的字段的子類添加了@Valid。
示例:B、C 類有一些字段具有非空等約束
公共 A { @Valid private B bCommand; @Valid private C cCommand; 私有D dCommand;}
添加回答
舉報