简体   繁体   English

SpringBoot REST Api JSON 验证

[英]SpringBoot REST Api JSON validation

I have a simple springboot app with one Rest api.我有一个简单的 springboot 应用程序,其中包含一个 Rest api。 I want to validate the request parameters are not null/empty.我想验证请求参数不为空/为空。 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. 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;

I also have a contained Feature class that I need to be validated( all fields required and not null or empty)我还有一个需要验证的包含功能 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;

}

You should annotate the controller class as @Validated and add @Valid annotation to the request parameter:您应该将 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM