美文网首页
SpringBoot参数校验

SpringBoot参数校验

作者: 我弟是个程序员 | 来源:发表于2017-11-27 16:24 被阅读0次

参数校验在项目中是很常见的。SpringBoot使用 @Valid注解 + BindingResult 来实现参数校验

1.新建User对象
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;

import javax.validation.constraints.Max;
import javax.validation.constraints.Min;

@Data //自动添加getter setter toString方法
public class User {
    @NotEmpty(message="姓名不能为空")
    private String name;
    @Max(value = 100, message = "年龄不能大于 100 岁")
    @Min(value= 18 ,message= "必须年满 18 岁!" )
    private int age;
    @NotEmpty(message="密码不能为空")
    @Length(min=6,message="密码长度不能小于 6 位,不能多于18位",max = 18)
    private String pass;
}

2.参数校验
    @RequestMapping("/saveUser")
    public String saveUser(@Valid User user, BindingResult result) {
        System.out.println("user:"+user);
        if(result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                System.out.println(error.getCode() + "-" + error.getDefaultMessage());
            }
            return "error";
        }
        return "success";
    }
3.测试
http://127.0.0.1:8081/saveUser
测试结果

相关文章

  • SpringBoot参数校验和国际化使用

    一、参数校验 springboot 使用校验框架validation校验方法的入参 SpringBoot的Web组...

  • SpringBoot 参数校验

    在后端开发的过程中,验证前端参数的合法性是一个必不可少的步骤。但是参数验证会产生大量的样板代码,导致代码可读性差。...

  • SpringBoot参数校验

    参数校验在项目中是很常见的。SpringBoot使用 @Valid注解 + BindingResult 来实现参数...

  • SpringBoot 参数校验

    在web项目开发过程中,参数的校验是十分重要的。入参少的情况下使用if else即可处理,但是入参多而的情况下if...

  • springboot 参数校验

    https://reflectoring.io/bean-validation-with-spring-boot/...

  • springboot参数校验

    概述 使用spring validation可以对用户输入参数进行校验,用户参数可以是一个bean,也可以是简单数...

  • springboot 参数校验详解

    在日常开发写rest接口时,接口参数校验这一部分是必须的,但是如果全部用代码去做,显得十分麻烦,spring也提供...

  • SpringBoot 表单参数校验

    在前后端分离如此盛行的今天,普遍使用 Json 进行数据交互,为了保证数据的完整与有效性,我们一般会在前端提交数据...

  • springboot 参数校验详解

    1. PathVariable 校验 在定义 Restful 风格的接口时,通常会采用 PathVariable ...

  • SpringBoot 接口参数校验

    springboot2.3版本以后需要引入validation依赖: 或者使用: 一、 @Valid和@Valid...

网友评论

      本文标题:SpringBoot参数校验

      本文链接:https://www.haomeiwen.com/subject/zredbxtx.html