簡體   English   中英

SpringBoot REST Api JSON 驗證

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM