[英]Json request validation for mandatory field - springboot rest-api
[英]SpringBoot REST Api JSON validation
我有一个简单的 springboot 应用程序,其中包含一个 Rest api。 我想验证请求参数不为空/为空。 I convert the json into a java object and from here I want to validate they have all the required fields and are not null or not empty.(The object is not getting saved to db) I am currently using javax validation methods without any success.
@RestController
public class GardenController{
@PostMapping(value = "/submit")
public ResponseEntity submit(
@RequestPart(value="garden", required=true) Garden garden
) throws Exception {
}
}
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotEmpty;
import java.util.Arrays;
@Getter
@Setter
public class Garden{
public Garden( String[] address, String area, String location, Feature
feature) {
this.address= address;
this.area= area;
this.location= location;
this.feature= feature;
}
public Garden() {
}
@JsonProperty("address")
@NotEmpty(message = "address is required")
private String [] address = null;
@JsonProperty("area")
@NotEmpty(message = "area is required")
private String area= null;
@JsonProperty("location")
@NotEmpty(message = "location is required")
private String location= null;
@JsonProperty("feature")
@NotEmpty(message = "feature is required")
private Feature feature= null;
我还有一个需要验证的包含功能 class(所有字段都是必需的,而不是 null 或空)
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotEmpty;
@Getter
@Setter
public class Feature {
public Feature () {
}
public Feature (String construction, String type) {
this.construction = construction;
this.type = type;
}
@NotEmpty(message = "construction is required")
private String construction;
@NotEmpty(message = "type is required")
private String type;
}
您应该将 controller class 注释为 @Validated 并将 @Valid 注释添加到请求参数:
import org.springframework.validation.annotation.Validated;
import javax.validation.Valid;
// ...
@RestController
@Validated
public class GardenController{
@PostMapping(value = "/submit")
public ResponseEntity submit(
@RequestPart(value="garden", required=true) @Valid Garden garden
) throws Exception {
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.