@valid(validated)校验(验证) 的使用注意事项

首先先查看springboot项目有没有@valid和@validated依赖,没有的话就导入依赖

<dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-validationartifactId>
dependency>

1:对于只有参数的时候使用,需要在类上加@validated,验证才生效

/**
 * @Author xqf
 * @since 2023-08-27
 */
@RestController
@RequestMapping("/sys")
@Api(tags="参数校验")
@Slf4j
@Validated
public class ValidTestController {
	@ApiOperation("验证参数")
	@RequestMapping(value = "/validParameter", method = RequestMethod.POST)
	public Result<JSONObject> checkValidParameter(@NotBlank String validObject) {
		Result<JSONObject> result = new Result<JSONObject>();
		return result;
	}
}

2:验证对象里面的属性如下

package org.jeecg.modules.system.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

/**
 * @Author xu
 * @create 2023/8/27 11
 */
@RestController
@RequestMapping("/sys")
@Api(tags="参数校验")
@Slf4j
public class ValidTestController {
	@ApiOperation("验证对象")
	@RequestMapping(value = "/validObjec", method = RequestMethod.POST)
	public Result<JSONObject> checkValidObjec(@RequestBody @Valid ValidObject validObject)  {
		Result<JSONObject> result = new Result<>();
		return result;
	}
}

注意:验证对象,@NotBlank 注解不适用于整数类型,只能使用@NotNull或@Min(value)

package org.jeecg.modules.system.controller;

import lombok.Data;
import org.jeecg.modules.system.vo.dto.Age;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;

/**
 * 验证对象
 * @Author xu
 * @create 2023/8/27 11
 */
@Data
public class ValidObject {

    @NotNull(message = "年龄不可为空")
    private Integer age;

    @NotBlank(message = "名字不可为空")
    private String name;
    private Integer phone;
}

3:如果对象继承Map的话,验证对象时,都获取不了对象,只能通过map的get(“属性”)获取

你可能感兴趣的:(java,spring,boot,spring)