springboot 请求接口验证入参字段是否为空

先上代码看一下



import com.hisense.common.utils.ResultVOUtil;
import com.hisense.common.vo.ResultVO;
import com.hisense.home.model.SysLoginModel;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * @author Arthur.yu
 * @date 2021/8/10 0010
 */
@RestController
@RequestMapping("/sys")
@Api(tags="用户登录")
@Slf4j
public class LoginController {

    @ApiOperation("登录接口")
    @PostMapping("/login")
    public ResultVO login(@Valid @RequestBody SysLoginModel sysLoginModel, BindingResult bindingResult){

        if (bindingResult.hasErrors()){
            return ResultVOUtil.error(1000,bindingResult.getAllErrors().get(0).getDefaultMessage());
        }


        return ResultVOUtil.success();
    }
}


import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.NotEmpty;

/**
 * @author Arthur.yu
 * @date 2021/8/10 0010
 */
@Data
@ApiModel(value="登录对象", description="登录对象")
public class SysLoginModel {
    @NotEmpty(message = "手机号不能为空")
    @ApiModelProperty(value = "账号")
    private String userName;
    @NotEmpty(message = "密码不能为空")
    @ApiModelProperty(value = "密码")
    private String password;
    @NotEmpty(message = "验证码不能为空")
    @ApiModelProperty(value = "验证码")
    private String captcha;
}

@Valid 如果爆红,请检查一下springboot版本是否大于 2.3.0


image.png

解决办法有两种。第一种是降低springboot版本小于2.3.0 第二种办法是比较推荐的,就是pom新增如下:

        
            org.springframework.boot
            spring-boot-starter-validation
        

你可能感兴趣的:(springboot 请求接口验证入参字段是否为空)