【问题标题】:SpringBoot REST Api JSON validationSpring Boot REST Api JSON 验证
【发布时间】:2020-07-01 09:08:03
【问题描述】:

我有一个带有一个 Rest api 的简单 springboot 应用程序。我想验证请求参数不为空/为空。我将 json 转换为 java 对象,从这里我想验证它们是否具有所有必需的字段并且不为空或不为空。(对象未保存到数据库) 我目前正在使用 javax 验证方法,但没有任何成功。

@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;

我还有一个需要验证的包含要素类(所有字段都是必需的,不为空或为空)

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;

}

【问题讨论】:

  • 在您的控制器方法中尝试在 Garden 之前添加 @Valid。还可以尝试将@Validated 添加到您的控制器类中。
  • 您需要指示 Spring MVC 验证您的对象,您需要将 @Valid 添加到您的方法参数(在 @RequestPart 旁边)。要验证嵌入的对象,您还需要将 @Valid 添加到该字段。您不需要控制器上的@Validated(如@pirho 所建议的那样)用于不同的目的。
  • 感谢@M.Deinum,这很有效。但是我收到 400 响应,但没有收到我设置的消息:{“timestamp”:“2020-07-01T09:43:58.052+00:00”,“status”:400,“error”:“Bad Request” , "消息": "", }
  • 因为这是出现问题时的通用 400 消息。如果您需要更详细的信息,您需要添加自己的异常处理。
  • 那么如果消息没有被输入到 HTTP 响应消息中,那么它在哪里使用呢?

标签: java spring-boot validation spring-rest


【解决方案1】:

您应该将控制器类注释为@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 { 
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-04
    • 2020-09-27
    • 2017-03-17
    • 1970-01-01
    • 2016-04-23
    • 2020-05-22
    • 2016-12-01
    • 2015-06-03
    相关资源
    最近更新 更多