这里我们介绍以下自定义的校验器的简单的使用示例

一、包结构和主要文件

二、代码

1.自定义注解文件MyConstraint

package com.knyel.validator;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; @Target({ElementType.METHOD,ElementType.FIELD})//注解可以标注在什么元素上
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyConstraintValidator.class)
public @interface MyConstraint {
String message(); Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {};
}

2.自定义校验逻辑文件MyConstraintValidator

package com.knyel.validator;

import com.knyel.service.HelloKnyel;
import org.springframework.beans.factory.annotation.Autowired; import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext; //ConstraintValidator<A,T>
//A参数:表示要验证的注解
//T参数:表示要验证的东西是什么类型
public class MyConstraintValidator implements ConstraintValidator<MyConstraint,Object> { @Autowired
HelloKnyel helloKnyel; @Override
public void initialize (MyConstraint myConstraint){
//校验器初始化的时候做的一些工作
System.out.println("myvalidator init");
} /*
真正的校验逻辑
Object o :传进来的校验的值
ConstraintValidatorContext constraintValidatorContext :校验的上下文
*/
@Override
public boolean isValid (Object value, ConstraintValidatorContext constraintValidatorContext){
//处理校验逻辑
helloKnyel.welcome("knyel");
System.out.println(value);
//true代表校验成功,false代表校验失败
return false;
}
}

3.在2中isValid方法中调用的校验逻辑业务HelloKnyelImpl及接口

package com.knyel.service;

public interface HelloKnyel {
String welcome(String name);
}
package com.knyel.service.impl;

import com.knyel.service.HelloKnyel;
import org.springframework.stereotype.Service; @Service
public class HelloKnyelImpl implements HelloKnyel { @Override
public String welcome (String name){
System.out.println("welcome");
return "hello knyel";
}
}

4.待校验的实体

package com.knyel.dto;

import com.fasterxml.jackson.annotation.JsonView;
import com.knyel.validator.MyConstraint;
import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.Past;
import java.util.Date; public class User { public interface UserSimpleView {};
public interface UserDetailView extends UserSimpleView {}; private String id;
@MyConstraint(message = "测试校验器")
private String username;
@NotBlank(message="密码不能为空")
private String password;
@Past(message = "生日必须是过去的时间")
private Date birthday; @JsonView(UserSimpleView.class)
public String getUsername (){
return username;
} public void setUsername (String username){
this.username = username;
}
@JsonView(UserDetailView.class)
public String getPassword (){
return password;
} public void setPassword (String password){
this.password = password;
} @JsonView(UserSimpleView.class)
public String getId (){
return id;
}
@JsonView(UserSimpleView.class)
public void setId (String id){
this.id = id;
} public Date getBirthday (){
return birthday;
} public void setBirthday (Date birthday){
this.birthday = birthday;
} @Override
public String toString (){
return "User{" + "id='" + id + '\'' + ", username='" + username + '\'' + ", password='" + password + '\'' + ", birthday=" + birthday + '}';
}
}

5.controller

    @PutMapping("/{id:\\d+}")
public User update (@Valid @RequestBody User user, BindingResult errors){
if (errors.hasErrors()) {
errors.getAllErrors().stream().forEach((ObjectError error) ->{
// FieldError fieldError=(FieldError) error;
// String message=fieldError.getField()+":"+fieldError.getDefaultMessage();
System.out.println(error.getDefaultMessage());
});
}
System.out.println(user.getId());
System.out.println(user.getUsername());
System.out.println(user.getPassword());
System.out.println(user.getBirthday());
user.setId("1");
return user;
}

执行测试用例后

myvalidator init
welcome
knyel
测试校验器
1

spring mvc controller中的参数验证机制(二)的更多相关文章

  1. spring mvc controller中的参数验证机制(一)

    一.验证用到的注解 @Valid 对传到后台的参数的验证 @BindingResult 配合@Valid使用,验证失败后的返回 二.示例 1.传统方式 @PostMapping public User ...

  2. Spring MVC Controller中解析GET方式的中文参数会乱码的问题(tomcat如何解码)

    Spring MVC Controller中解析GET方式的中文参数会乱码的问题 问题描述 在工作上使用突然出现从get获取中文参数乱码(新装机器,tomcat重新下载和配置),查了半天终于找到解决办 ...

  3. spring mvc controller中获取request head内容

    spring mvc controller中获取request head内容: @RequestMapping("/{mlid}/{ptn}/{name}") public Str ...

  4. Spring MVC Controller中GET方式传过来的中文参数会乱码的问题

    Spring MVC controller 这样写法通常意味着访问该请求,GET和POST请求都行,可是经常会遇到,如果碰到参数是中文的,post请求可以,get请求过来就是乱码.如果强行对参数进行了 ...

  5. spring MVC controller中的方法跳转到另外controller中的某个method的方法

    1. 需求背景     需求:spring MVC框架controller间跳转,需重定向.有几种情况:不带参数跳转,带参数拼接url形式跳转,带参数不拼接参数跳转,页面也能显示. 本来以为挺简单的一 ...

  6. spring mvc Controller中使用@Value无法获取属性值

    在使用spring mvc时,实际上是两个spring容器: 1,dispatcher-servlet.xml 是一个,我们的controller就在这里,所以这个里面也需要注入属性文件 org.sp ...

  7. spring mvc controller中的异常封装

    http://abc08010051.iteye.com/blog/2031992 一直以来都在用spring mvc做mvc框架,我使用的不是基于注解的,还是使用的基于xml的,在controlle ...

  8. 在Spring MVC Controller中注入HttpServletRequest对象会不会造成线程安全的问题

    做法: 1.比如我们在Controller的方法中,通常是直接将HttpServletRequest做为参数,而为了方便节省代码,通常会定义为全局变量,然后使用@Autowire注入. 说明: 1.观 ...

  9. 本版本延续MVC中的统一验证机制~续的这篇文章,本篇主要是对验证基类的扩展和改善(转)

    本版本延续MVC中的统一验证机制~续的这篇文章,本篇主要是对验证基类的扩展和改善 namespace Web.Mvc.Extensions { #region 验证基类 /// <summary ...

随机推荐

  1. freemarker语法介绍及其入门教程实例

    # freemarker语法介绍及其入门教程实例 # ## FreeMarker标签使用 #####一.FreeMarker模板文件主要有4个部分组成</br>####  1.文本,直接输 ...

  2. 利用STM32CubeMX来生成USB_HID_Mouse工程【添加ADC】(2)【非dma和中断方式】

    上回讲到怎么采集一路的adc的数据,这次我们来采集两路的数据. 现在直接修改原先的代码 /* Private variables ----------------------------------- ...

  3. 【mysql】批量更新数据

    概述 批量更新mysql数据表数据,上网搜索基本都会说4~5方法,本人使用的更新方式为: INSERT ... ON DUPLICATE KEY UPDATE Syntax 可参见官方网站:inser ...

  4. Docker镜像常用命令

    镜像(image)是Docker三大核心概念中最重要的,是运行容器的前提. Docker运行容器前需要本地存在对应的镜像,如果镜像没保存在本地,Docker会尝试先从默认镜像仓库下载(默认使用Dock ...

  5. jenkines的工作区目录位置查找

    先找到jenkines的主目录 系统-系统配置 然后工作区在主目录的workspace文件夹里面

  6. [UE4]Native Widget Host

    一.Native Widget Host是一个容器,它可以包含一个Slate UI 二.Native Widget Host应该用在当你需要把一个Slate UI 放到UMG中的时候,只有这个时候才需 ...

  7. 知识点:SQL中char、varchar、text区别

    Char为定长,varchar,text为变长. 1.CHAR.CHAR存储定长数据很方便,CHAR字段上的索引效率级高,比如定义char(10),那么不论你存储的数据是否达到了10个字节,都要占去1 ...

  8. Cache基本原理之:结构

    转载自:https://www.jianshu.com/p/2b51b981fcaf Cache entries 数据在主存和缓存之间以固定大小的”块(block)”为单位传递,也就是每次从main ...

  9. winCVS 使用的一个小要点

    对于版本管理软件CVS,可以在Linux中使用命令来管理. 但是 在windows 界面下,也可以使用 winCVS 工具来管理. 现在 讲一下 如何 在 winCVS 登陆 CVS 帐号 和 密码: ...

  10. dubbo面试题,会这些说明你真正看懂了dubbo源码

    整理了一些dubbo可能会被面试的面试题,感觉非常不错.如果你基本能回答说明你看懂了dubbo源码,对dubbo了解的足够全面.你可以尝试看能不能回答下.我们一起看下有哪些问题吧? 1.dubbo中& ...