SpringBoot使用Validator校验框架

SpringBoot参数校验@Valid 和 @Validated注解使用详解 阅读详情
Hibernate Validator 简介

Hibernate Validator是Hibernate项目中的一个数据校验框架,是Bean Validation 的参考实现,Hibernate Validator除了提供了JSR 303规范中所有内置constraint 的实现,还有一些附加的constraint。

Hibernate Validator 作用
  • 数据校验逻辑和业务代码分离,程序解耦性提高
  • 统一且规范的校验格式,规避了大量重复的数据校验代码
  • 精力更加集中于业务代码
Hibernate Validator 使用

项目中,主要通过接口API的接口入参校验和封装工具类在代码中使用两种方式

引入jar包
<!-- 使用SpringBoot框架 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

<!-- 直接引用jar包 -->
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.9.Final</version>
</dependency>
Java对象添加约束

级联校验需要添加@Valid注解

import com.ai.chinapost.crm.mdb.mgr.common.ValidateGroup;
import lombok.Data;
import org.hibernate.validator.constraints.NotBlank;

import javax.validation.Valid;
import java.util.List;

/**
 * @date 2021/01/11
 */
@Data
public class CltMktOccuAndIncmBO {
    /**
     * 保存或修改标识 1:保存 2:修改
     */
    @NotBlank(message = "保存或修改标识不能为空" ,groups = ValidateGroup.CltMktOccuAndIncm.class)
    private String saveOrUpdate;
    
    /**
     * 更新人编码
     */
    @NotBlank(message = "更新人编码必填" ,groups = ValidateGroup.CltMktOccuAndIncm.class)
    private String updatedByUserCode;
    /**
     * 更新人所属机构编码
     */
    @NotBlank(message = "更新人所属机构编码必填" ,groups = ValidateGroup.CltMktOccuAndIncm.class)
    private String updatedByOrgCode;
    /**
     * 统计时间
     */
    @NotBlank(message = "统计时间必填" ,groups = ValidateGroup.CltMktOccuAndIncm.class)
    private String statisDate;

    @Valid
    private List<CltMktOccuAndIncmDetailBO> cltMktOccuAndIncmDetailList;
}

校验组设置
/**
 * @date 2020/7/21
 */
public interface ValidateGroup {
    interface CltMktOccuAndIncm {
    }
}
API接口入参校验
  • 定义接口
      接口入参需要添加@Validated注解,进行参数校验
@PostMapping("/saveDist")
@ResponseBody
    public ResponseEntity dist(@Validated(ValidateGroup.CltMktOccuAndIncm.class) @RequestBody TrgtMktOcBase entity) throws CommonException {
        ResponseEntity resp = distTrgtFacadeConsumer.dist(entity);
        return resp;
    }

  • postMan测试结果
请求报文:
{
  "saveOrUpdate": "",
  "updatedByUserCode": "20000",
  "updatedByOrgCode": "100",
  "statisDate": "",
  "cltMktOccuAndIncmDetailList": [
    {
      "provId": "",
      "provName": "安徽"
    },
    {
      "provId": "370000",
      "provName": "山东"
    }
  ]
}
响应报文:
{
    "code": 400,
    "message": "statisDate:统计时间必填 saveOrUpdate:保存或修改标识不能为空 cltMktOccuAndIncmDetailList[0].provId:省份编码必填 参数值有误"
}

封装工具类校验
  • 工具类中的Validator对象有两种方式获取(选其一即可)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

import javax.validation.Validator;

/**
 * @date 2021/01/13
 */
@Component
public class ValidatorConfig {

    @Bean(name = "validator")
    @Primary
    public Validator validator() {
        return new LocalValidatorFactoryBean();
    }
}

import lombok.Data;
import org.hibernate.validator.HibernateValidator;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * 校验工具类
 *
 * @date 2021/01/13
 */
@Component
public class ValidationUtil implements ApplicationContextAware {

    private static final ValidationUtil Instance = new ValidationUtil();

    public static ValidationUtil getInstance() {
        return Instance;
    }

    private static Validator validator;

    // 结合ValidatorConfig类通过Spring容器获取
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ValidationUtil.validator = (Validator) applicationContext.getBean("validator");
    }

    // 直接通过Validation类获取对象
    // 开启快速结束模式 failFast (true)
    private static Validator validator1 = Validation.byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory().getValidator();

    /**
     * 校验对象
     *
     * @param obj    bean对象
     * @param groups 校验组,必须是一个接口
     * @param <T>
     * @return Optional<ValidResult>
     */
    public <T> Optional<ValidResult> validateBean(T obj, Class<?> groups) {
        ValidResult result = Instance.new ValidResult();
        Set<ConstraintViolation<T>> violationSets = validator.validate(obj, groups);

        if (CollectionUtils.isEmpty(violationSets)) {
            return Optional.empty();
        }

        for (ConstraintViolation<T> violation : violationSets) {
            result.addError(violation.getPropertyPath().toString(), violation.getMessage());
        }

        return Optional.of(result);
    }

    /**
     * 校验对象的某一个属性
     *
     * @param obj          bean对象
     * @param propertyName 属性名称
     * @param <T>
     * @return Optional<ValidResult>
     */
    public <T> Optional<ValidResult> validateProperty(T obj, String propertyName) {
        ValidResult result = Instance.new ValidResult();
        Set<ConstraintViolation<T>> violationSets = validator.validateProperty(obj, propertyName);

        if (CollectionUtils.isEmpty(violationSets)) {
            return Optional.empty();
        }

        for (ConstraintViolation<T> violation : violationSets) {
            result.addError(violation.getPropertyPath().toString(), violation.getMessage());
        }

        return Optional.of(result);
    }

    @Data
    public class ValidResult {

        /**
         * 错误信息
         */
        private List<ErrorMessage> errors;

        public ValidResult() {
            this.errors = new ArrayList<>();
        }

        /**
         * 获取所有验证信息
         *
         * @return 集合形式
         */
        public List<ErrorMessage> getAllErrors() {
            return errors;
        }

        /**
         * 获取所有验证信息
         *
         * @return 字符串形式
         */
        public String getErrors() {
            StringBuilder sb = new StringBuilder();
            for (ErrorMessage error : errors) {
                sb.append(error.getPropertyPath()).append(":").append(error.getMessage()).append(" ");
            }
            return sb.toString();
        }

        public void addError(String propertyName, String message) {
            this.errors.add(new ErrorMessage(propertyName, message));
        }
    }

    @Data
    private class ErrorMessage {
        private String propertyPath;

        private String message;

        public ErrorMessage() {
        }

        public ErrorMessage(String propertyPath, String message) {
            this.propertyPath = propertyPath;
            this.message = message;
        }
    }

}

  • 测试代码

也可不指定分组(groups),会默认使用Default.class分组

public ResponseEntity saveCltMktOccuAndIncm(String params) {
         // 校验参数
        Class cltMktOccuAndIncm = ValidateGroup.CltMktOccuAndIncm.class;
        CltMktOccuAndIncmBO cltMktOccuAndIncmBO = JSON.parseObject(params, CltMktOccuAndIncmBO.class);
        Optional<ValidationUtil.ValidResult> validResult = ValidationUtil.getInstance().validateBean(cltMktOccuAndIncmBO, cltMktOccuAndIncm);
        if (validResult.isPresent()) {
            ValidationUtil.ValidResult errMessage = validResult.get();
            return ResponseEntity.fail(ResponseEnum.DATA_ERROR, errMessage.getErrors());
        }

        return cltMktOccuAndIncmFacade.saveOrModifyCltMktOccuAndIncm(cltMktOccuAndIncmBO);
    }

  • 测试结果
响应报文:
{
    "code": 400,
    "message": "statisDate:统计时间必填 saveOrUpdate:保存或修改标识不能为空 cltMktOccuAndIncmDetailList[0].provId:省份编码必填 参数值有误"
}

其他常用的constranint
@AssertFalse @AssertTrue 检验boolean类型的值

@DecimalMax @DecimalMin 限定被标注的属性的值的大小

@Digits(intege=,fraction=) 限定被标注的属性的整数位数和小数位数

@Future 检验给定的日期是否比现在晚

@Past 校验给定的日期是否比现在早

@Max 检查被标注的属性的值是否小于等于给定的值

@Min 检查被标注的属性的值是否大于等于给定的值

@NotNull 检验被标注的值不为空

@Null 检验被标注的值为空

@Pattern(regex=,flag=) 检查该字符串是否能够在match指定的情况下被regex定义的正则表达式匹配

@Size(min=,max=) 检查被标注元素的长度

@Valid 递归的对关联的对象进行校验

文章借鉴处

  • https://www.jianshu.com/p/0bfe2318814f
【SpringBoot】整合fluent-validator数据校验框架 本文介绍了SpringBoot整合FluentValidator数据校验框架的完整方案,FluentValidator数据校验框架是一个流式风格的数据校验框架,可以兼容HibernateValidator,可以支持自字义校验。 阅读详情

相关推荐

学术版GPT安装教程——保姆版(附带原生GPT注册教程)

学术版GPT图文安装教程

DBenD的博客 2万+

Springboot项目参数校验(Validator)

Springboot项目参数校验(Validator)

nuoya989的博客 5364

从零搭建企业级AI网关:基于LiteLLM的安全防护体系设计

本文详细介绍了如何从零搭建企业级AI网关,基于LiteLLM构建全面的安全防护体系。内容涵盖分层防御架构、敏感数据处理、合规性配置与审计追踪,以及生产环境部署策略,助力企业安全高效地集成LLM技术,确保数据安全和合规性。

qq_27496129的博客 1292

SpringBoot使用validator进行参数校验

Validated、@Valid和BindingResult@Validated、@Valid和BindingResultBean Validation是Java定义的一套基于注解的数据校验规范,比如@Null、@NotNull、@Pattern等,它们位于 javax.validation.constraints这个包下。目前已经从JSR 303的1.0版本升级到JSR 349的1.1版本,再到JSR 380的2.0版本。

csdnzhang365的博客 5307

VMvare 桥接模式无法联网、没有未桥接的主机网络适配器,无法将网络更改为桥接状态。

很多程序员,整天沉浸在业务代码的 CRUD 中,业务中没有大量数据做并发,缺少实战经验,对并发仅仅停留在了解,做不到精通,所以总是与大厂擦肩而过。我把私藏的这套并发体系的笔记和思维脑图分享出来,理论知识与项目实战的结合,我觉得只要你肯花时间用心学完这些,一定可以快速掌握并发编程。《互联网大厂面试真题解析、进阶开发核心学习笔记、全套讲解视频、实战项目源码讲义》点击传送门即可获取!战项目源码讲义》点击传送门即可获取!**

q16974058的博客 4332

CH340以及CH系列USB转串口驱动下载

在之前使用USB转串口时,很多时候大家可能会不知道去哪下载驱动,然后百度随便下载一个,但往往鱼龙混杂且版本不一,所以今天特意整理一下CH340驱动以及CH系列的官方驱动下载地址,方便大家进行下载也方便自己后期查找,所有链接皆指向官方下载链接,每次下载都可获取官方当前最新驱动。 CH340/CH341 Windows驱动下载链接:CH341SER.EXE下载链接 Linux驱动下载链接:CH341SER_LINUX.ZIP下载链接 Andr...

OIDCAT的博客 4万+

SpringBoot:参数校验的使用(validator)

SpringBoot:参数校验的使用(validator)

拒绝熬夜啊的博客 6160

FreeRTOS面试题汇总

如果一个低优先级的任务持有一个信号量,高优先级的任务想要用这个信号量,造成的死锁怎么解决。12.FreeRTOS的多任务之间如何去进行通信的,什么方法,它实现原理是什么。任务间数据传输一共有三种形式,用的最多的是消息队列,其次是全局变量和信号量。简历上写了了解RTOS,问了rtos的问题,用过哪些函数。讲解FreeRtos原理,调度机制,底层原理,代码调用。FreeRTOS,你的三个任务控制,请问你是怎么实现的。freertos中EventBits_t是干啥的?freertos使任务切换的方式有哪些?

weixin_45636780的博客 1万+

SpringBoot的参数校验器 - Validator

使用框架自带的Validated验证器,能很大程度的简化开发,提高开发效率。

qq_45515182的博客 4861

APP抓包-代理转发绕过反代理+Xposed绕过证书校验

而这里的牛牛不止设置了反代理还设置了证书校验,一闪而过的三个数据包就是在校验证书。而proxifier工具的转发机制获取的是网络接口出口数据,相当于是在网络接口设代理。这个时候就可以在夜神打开牛牛开始抓包了,打开牛牛可以看到proxifier有夜神流量通过。关闭代理之后牛牛就正常了,可恶的牛牛啊,这样我没办法抓包啊,怎么办啊。模拟器开启代理,burp开启监听。打开牛牛app,牛牛不在报错。牛牛app检测的是系统代理,也就是在模拟器或手机上设置的代理。再在浏览器下载两个模块,在夜神安装,用来屏蔽证书校验。

xiaoheizi的博客 7532

保姆级教程:用STM32CubeMX HAL库搞定ESP8266连接,附串口printf调试全流程

本文提供了一份详细的STM32CubeMX HAL库教程,指导开发者如何实现ESP8266无线模块的连接与调试。从开发环境搭建、串口配置到AT指令通信解析,涵盖了物联网开发中的关键步骤和常见问题解决方案,帮助开发者快速掌握STM32与ESP8266的集成技术。

weixin_28273593的博客 504

【SpringBoot】——Hibernator-Validator校验框架

介绍 首先说下大家常用的hibernate-validator,它是对JSR-303/JSR-349标准的实现,然后spring为了给开发者提供便捷集成了hibernate-validator,默认在springmvc模块。 依赖 本文所介绍皆在springboot应用的基础上,首先加上web模块: <dependency> <groupId>org.sp...

山山来驰的博客 4194

【车载以太网】ATU(Address Translation Unit / Address Table Unit)

【车载以太网】ATU(Address Translation Unit / Address Table Unit)

天赐好车的博客 153

SpringBoot 中使用 validator 框架优雅地校验参数

举个例子:业务系统的用户需要保证其唯一性,用户属性不能与其他用户产生冲突,不允许与数据库中任何已有用户的用户名称、手机号码、邮箱产生重复。如:保存 User 的时候,userId 是可空的,但是更新 User 的时候,userId 的值必须 >= 1L;接口的第一个参数是 自定义注解类型,第二个参数是 被注解字段的类,因为需要校验多个参数,我们直接传入用户对象。在日常的开发中,为了防止非法参数对业务造成影响,需要对接口的参数进行校验,以便正确性地入库。的标准方式,借助自定义校验注解完成业务规则校验。

sco5282的博客 8567

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

SpringBoot 项目中整合数据校验框架 hibernate-validator

早期的网站,用户输入一个邮箱地址,需要将邮箱地址发送到服务端,服务端进行校验,校验成功后再给前端一个响应。自从有了 JavaScript 后,校验工作可以放在前端去执行。那么为什么还需要服务端校验呢?因为前端传来的数据不可信,前端很容易获取到后端的接口,如果有人直接调用接口,就可能会出现非法数据,因此服务端也要数据校验。总的来说:校验参数基本上是一个体力活,而且冗余代码繁多,也影响代码的可读性,我们需要一个比较优雅的方式来解决这个问题。Hibernate Validator 框架刚好解决了这个问题,可以很优

华仔仔的博客 1929

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

springboot 配置 Validator 校验框架国际化 支持快速返回

1、国际化资源 使用IDEA创建资源组 2、编写配置 application.yml 增加国际化目录配置 增加国际化配置类 从请求头获取多语言关键字 /** * 国际化配置 * * @author Lion Li */ @Configuration public class I18nConfig { @Bean public LocaleResolver localeResolver() { return new I18nLocaleResolver(); } /**

李虹柏的博客 3758

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

SpringBoot整合Validator

String message() default "请输入中文";Class

努力分享一些干货 1251

springboot- hibernate-validator(校验框架)使用

概述: hibernate-validator是Hibernate项目中的一个数据校验框架,是Bean Validation 的参考实现,hibernate-validator除了提供了JSR 303规范中所有内置constraint 的实现,还有一些附加的constraint 。使用hibernate-validator能够将数据校验从业务代码中脱离出来,增加代码可读性,同时也让数据校验变得更加...

Fly_Fly_Zhang的博客 813

Spring Boot 全局异常处理 与 Hibernate Validator校验框架整合

上述知识点,囊括了目前互联网企业的主流应用技术以及能让你成为“香饽饽”的高级架构知识,每个笔记里面几乎都带有实战内容。很多人担心学了容易忘,这里教你一个方法,那就是重复学习。打个比方,假如你正在学习 spring 注解,突然发现了一个注解@Aspect,不知道干什么用的,你可能会去查看源码或者通过博客学习,花了半小时终于弄懂了,下次又看到@Aspect 了,你有点郁闷了,上次好像在哪哪哪学习,你快速打开网页花了五分钟又学会了。从半小时和五分钟的对比中可以发现多学一次就离真正掌握知识又近了一步。

erghtt的博客 705

Springboot接口参数校验

在设计接口时我们通常需要对接口中的非法参数做校验,以降低在程序运行时因为一些非法参数而导致程序发生异常的风险,例如登录的时候需要校验用户名密码是否为空,创建用户的时候需要校验邮件、手机号码格式是否准确。如果你的一个实体中的字段某一些是新增的时候必传,某一些修改时又不用传,那么对于不用传的字段肯定不需要校验的,这时候如果我们共用一个实体作为多个接口参数那肯定存在兼容问题,此时你就可以考虑将参数分组判断。接口的第一个参数是 自定义注解类型,第二个参数是 被注解字段的类。addUserV2接口。

Spirit_NKlaus的专栏 1340

springboot使用hibernate validator校验

原文地址

weixin_45336205的博客 305

java vo 非空校验_GitHub - AggerChen/validator-test: SpringBoot参数校验框架使用demo

SpringBoot使用@Validated验证参数一、前言在前端传递参数给后台接口的时候,后端会对传递的参数做一个基础校验,以前是手动写if一个个验证,效率极其低,而且还做了很多重复工作。本例没有太对基础和原理讲解,直接上代码,就是要简单粗暴,大家先用起来再说。项目源代码请访问github获取。二、使用步骤Hibernate Validator在JSR 303校验框架中提供了很多注解类。此Hib...

weixin_42451850的博客 825

SpringBoot使用Validator进行参数校验(自定义校验,分组校验)

在实际开发中对于需要校验的字段都需要设置对应的业务提示,即message属性。@Data@Length(min = 6,max = 12,message = "appId长度必须位于6到12之间")@NotBlank(message = "名字为必填项")@Email(message = "请填写正确的邮箱地址")@NotEmpty(message = "级别不能为空")注解功能可以为null,如果不为null的话必须为false。

shenxiaomo1688的博客 2567

SpringBoot使用validation实现接口参数统一校验、统一返回值、自定义注解

SpringBoot接口参数统一校验、统一返回值、自定义注解看这一篇就够了

weixin_44506280的博客 2495
上一篇: Ubuntu 20.04.1 LTS安装OpenJDK
下一篇: SpringBoot配置和加载redis
香草味小布丁
博客等级 码龄10年 461粉丝 72原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值