广告
返回顶部
首页 > 资讯 > 后端开发 > Python >springboot 参数格式校验操作
  • 445
分享到

springboot 参数格式校验操作

2024-04-02 19:04:59 445人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

SpringBoot 参数格式校验 @Validated 字面意思校验 @RequestBody 该注解不用多说,意思是接收为JSON格式的参数 @Validated 字面意

SpringBoot 参数格式校验

@Validated

字面意思校验

在这里插入图片描述

@RequestBody

该注解不用多说,意思是接收为JSON格式的参数

@Validated

字面意思校验, 需要配合@NotBlank 或者 @NotNull 注解才能生效

进入到请求体参数中。

在这里插入图片描述

springboot 参数注解校验

1.添加依赖


<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

package com.xl.annotation;
import lombok.Data;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.Range;
import javax.validation.constraints.*;
import java.math.BigDecimal;
import java.util.Date;
@Data
public class User {

        @NotNull(message = "ID不能为空")
        @Range(min = 1, max = 100, message = "ID必须在1到100之间")
        private Integer id;

        @NotNull(message = "姓名不能为空")
        @Length(min = 2, max = 6, message = "姓名必须在2到6位之间")
        private String name;

        @NotNull(message = "余额不能为空")
        @DecimalMax(value = "30.50", message = "余额不能超过30.5")
        @DecimalMin(value = "1.50", message = "余额不能低于1.5")
        private BigDecimal amount;

        @NotNull(message = "生日不能为空")
        @Past(message = "生日必须是过去")
        private Date birthday;

        @NotBlank(message = "邮箱不能为空")
        @Email(message = "邮箱格式不正确")
        private String email;

        @NotBlank(message = "手机号不能为空")
        @Pattern(regexp = "^(((13[0-9])|(14[579])|(15([0-3]|[5-9]))|(16[6])|(17[0135678])|(18[0-9])|(19[89]))\\d{8})$", message = "手机号格式错误")
        private String phone;
}

2.controller层


package com.xl.annotation;
import io.swagger.annotations.api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.WEB.bind.annotation.*;
import javax.validation.ValidationException;
import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;

@RestController
@Validated
@Api(value = "手机验证",description = "手机验证")
public class MobileController {
@ApiOperation("手机验证")
@RequestMapping("/phone")
    public String mobilePattern( Phone phone){
        return "chengg";
    }
    @PostMapping("/getUser")
    @ApiOperation("手机验证12")
    public String getUserStr( @NotNull(message = "name 不能为空")@RequestParam String name,
                              @Max(value = 99, message = "不能大于99岁")@RequestParam Integer age) {
        return "name: " + name + " ,age:" + age;
    }
   
    private void validData(BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            StringBuffer sb = new StringBuffer();
            for (ObjectError error : bindingResult.getAllErrors()) {
                sb.append(error.getDefaultMessage());
            }
            throw new ValidationException(sb.toString());
        }
    }

    @PostMapping("/test")
    @ApiOperation(value = "测试", notes = "")
    public String  test(@ApiParam(name = "test", value = "参数", required = true) @Validated @RequestBody User test, BindingResult bindingResult) {
        validData(bindingResult);
        if(bindingResult.hasErrors()){
            String errORMsg = bindingResult.getFieldError().getDefaultMessage();
            return errorMsg;
        }
        return "参数验证通过";
    }
}

3.自定义一个抛出异常类


package com.xl.annotation;
import org.springframework.Http.httpstatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.ValidationException;
import java.util.Set;


@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(ValidationException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public String handle(ValidationException exception) {
        if(exception instanceof ConstraintViolationException){
            ConstraintViolationException exs = (ConstraintViolationException) exception;

            Set<ConstraintViolation<?>> violations = exs.getConstraintViolations();
            for (ConstraintViolation<?> item : violations) {
                //打印验证不通过的信息
                System.out.println(item.getMessage());
            }
        }
        return exception.getMessage();
    }
}

4.加一个当检测第一个参数不合法时立即返回错误不会继续进行校验


package com.xl.annotation;
import org.hibernate.validator.HibernateValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;

@Configuration
public class ValidatorConf {
    @Bean
    public Validator validator() {
        ValidatorFactory validatorFactory = Validation.byProvider( HibernateValidator.class )
                .configure()
                .failFast( true )
                .buildValidatorFactory();
        Validator validator = validatorFactory.getValidator();
        return validator;
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。

--结束END--

本文标题: springboot 参数格式校验操作

本文链接: https://www.lsjlt.com/news/129667.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • springboot 参数格式校验操作
    springboot 参数格式校验 @Validated 字面意思校验 @RequestBody 该注解不用多说,意思是接收为json格式的参数 @Validated 字面意...
    99+
    2022-11-12
  • springboot参数格式怎么校验
    这篇文章主要介绍“springboot参数格式怎么校验”,在日常操作中,相信很多人在springboot参数格式怎么校验问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”springboot参数格式怎么校验”的疑...
    99+
    2023-06-08
  • springboot 中怎么校验参数格式
    本篇文章给大家分享的是有关springboot 中怎么校验参数格式,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。springboot 参数格式校验@Validated 字面意思...
    99+
    2023-06-20
  • SpringBoot参数怎么校验
    本篇内容主要讲解“SpringBoot参数怎么校验”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“SpringBoot参数怎么校验”吧!使用传统方式的弊端public String&nb...
    99+
    2023-06-30
  • SpringBoot集成Validation参数校验
    本文实例为大家分享了SpringBoot集成Validation参数校验的具体代码,供大家参考,具体内容如下 1、依赖 SpringBoot在web启动器中已经包含validator...
    99+
    2022-11-12
  • SpringBoot怎么进行参数校验
    这篇文章主要讲解了“SpringBoot怎么进行参数校验”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“SpringBoot怎么进行参数校验”吧!介绍在日常的接口开发中,为了防止非法参数对业务...
    99+
    2023-06-30
  • SpringBoot参数校验Validator框架详解
    目录SpringBoot 如何进行参数校验1.集成Validator校验框架1.1. 引入依赖包1.2. 定义要参数校验的实体类1.3. 定义校验类进行测试1.4. 测试结果11.5...
    99+
    2022-11-13
  • SpringBoot参数校验的方法总结
    目录一、前言二、注解介绍三、添加依赖四、创建用于校验的实体类五、写一个测试用的接口六、在实体类中添加注解七、在 controller 方法中添加 Validated 注解八、添加全局...
    99+
    2022-11-12
  • Springboot 如何使用BindingResult校验参数
    目录使用BindingResult校验参数1、创建一个参数对象2、controller控制层写参数接收的入口3、传入参数和控制台打印结果4、常用校验注解BindingResult 作...
    99+
    2022-11-13
  • SpringBoot使用validation做参数校验说明
    目录1.添加依赖直接添加 hibernate-validator添加spring-boot-starter-validation添加spring-boot-starter-...
    99+
    2022-11-13
  • SpringBoot怎么使用validation做参数校验
    这篇文章主要介绍了SpringBoot怎么使用validation做参数校验的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SpringBoot怎么使用validation做参数校验文章都会有所收获,下面我们一起...
    99+
    2023-06-30
  • springboot接口参数校验JSR303的实现
    目录一、在controller接口处理校验异常二、统一异常处理三、错误码枚举类四、自定义参数校验注解在 javax.validation.constraints包中定义了非常多的校验...
    99+
    2022-11-13
    springboot接口参数校验JSR303 springboot JSR303
  • SpringBoot参数校验之@Valid怎么使用
    这篇文章主要介绍“SpringBoot参数校验之@Valid怎么使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“SpringBoot参数校验之@Valid怎么使用”文章能帮助大家解决问题。依赖&l...
    99+
    2023-07-02
  • SpringBoot后端数据校验实战操作指南
    目录1.为什么后端要进行数据校验?2.怎么使用数据校验?(要添加对应依赖)(1)在实体上的属性上添加校验注解:(2)在controller层的方法前加上注解@Validated开启数...
    99+
    2022-11-13
  • SpringBoot中@Pattern注解对时间格式校验方式
    目录SpringBoot @Pattern注解对时间格式校验1.需求背景2.实现案例@Pattern的用法下面是常用的正则表达式SpringBoot @Pattern注解对时间格式校...
    99+
    2022-11-12
  • SpringBoot参数校验的最佳实战教程
    目录前言hibernate-validator基本使用 引入依赖 编写需要验证对象 验证对象属性是否符合要求 验证规则 空/非空验证bool时间数学 字符串模板正则 SpringBo...
    99+
    2022-11-12
  • SpringBoot中参数校验的方法有哪些
    这篇文章给大家分享的是有关SpringBoot中参数校验的方法有哪些的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。一、前言在 Web 开发中经常需要对前端传过来的参数进行校验,例如格式校验、非空校验等,基本上每个...
    99+
    2023-06-15
  • SpringBoot各种参数校验的实例教程
    目录 简单使用引入依赖requestBody参数校验requestParam/PathVariable参数校验统一异常处理进阶使用分组校验嵌套校验集合校验自定义校验编程式校...
    99+
    2022-11-13
  • SpringBoot 如何自定义请求参数校验
    目录一、Bean Validation基本概念二、基本用法三、自定义校验3.1 自定义注解3.2 自定义Validator3.3 以编程的方式校验(手动)3.4 定义分组校验3.5 ...
    99+
    2022-11-12
  • SpringBoot参数校验之@Valid的使用详解
    目录简介依赖代码 测试测试1:缺少字段测试2:不缺少字段测试3:缺少字段,后端获取BindResult 简介 说明 本文用示例说明SpringBoot的@Vali...
    99+
    2022-11-13
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作