javax.validationは、リクエストパラメータの検証を実装するためのvalidation-api jarパッケージを提供し、ビジネスコードに面倒な検証ロジックを記述しないようにします。
以下に、ネストされた属性を書き込む方法について説明します。
パッケージcom.example.demo.controller;
インポートcom.example.demo.model.ActionParentModel;
インポートcom.example.demo.service.DemoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
@RestController
@RequestMapping( "/ hello")
public class DemoController {
@Autowired
private DemoService demoService;
@RequestMapping("/test")
public Boolean test(@RequestBody @Valid ActionParentModel req){
return true;
}
}
ActionParentModel.class
package com.example.demo.model;
import javax.validation.Valid;
import javax.validation.constraints.Size;
import java.io.Serializable;
import java.util.List;
public class ActionParentModel implements Serializable {
@Size(min = 1, max = 2)
private List<List<@Valid ActionModel>> updateConds;
public List<List<ActionModel>> getUpdateConds() {
return updateConds;
}
public void setUpdateConds(List<List<ActionModel>> updateConds) {
this.updateConds = updateConds;
}
}
ActionModel .class
package com.example.demo.model;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
public class ActionModel {
/**
* 条件类型(1:宝马,2:奔驰)
*/
@NotNull
@Range(min = 1, max = 2)
private Integer keyType;
@Pattern(regexp = "\\w+", message = "属性名格式不正确")
private String keyName;
public Integer getKeyType() {
return keyType;
}
public void setKeyType(Integer keyType) {
this.keyType = keyType;
}
public String getKeyName() {
return keyName;
}
public void setKeyName(String keyName) {
this.keyName = keyName;
}
}
List <List <@Valid ActionModel >> updateConds; @ValidはActionModelの前に配置する必要があります。そうしないと、検証が無効になります。
ここでのvalidation-apiは2.0.1.Final、バージョン1.1.0である必要があることに注意してください。Finalはサポートされていません。
2つのバージョン
2.0.1.Finalのソースコードの違いを比較します。
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Valid {
}
1.1.0最終:
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface Valid {
}
2.0.1.Finalはより多くのElementType.TYPE_USEをサポートしています。
Mavenの依存関係
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>