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

一、包结构和主要文件

二、代码

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. 第一章 C#入门 (Windows窗体应用程序)(一)

    我的第一个窗体应用程序(一) [案例说明]  在文本框中显示一行文字“Hello C#!”,单击[显示]按钮后在文本框中显示文字:单击[清除]按钮后清除文本框中的内容. [案例实现步骤] 1.新建项目 ...

  2. Delphi XE5 Android 调用 Google ZXing

    { Google ZXing Call demo Delphi Version: Delphi XE5 Version 19.0.13476.4176 By: flcop(zylove619@hotm ...

  3. 经典算法二分查找循环实现Java版

    二分查找 定义 二分查找(Binary Search)又称折半查找,它是一种效率较高的查找方法. 要求 (1)必须采用顺序存储结构 (2)必须按关键字大小有序排列 查找思路 首先将给定值K,与表中中间 ...

  4. C# 调用Tesseract实现OCR

    介绍 Tesseract是一个基于Apache2.0协议开源的跨平台ocr引擎,支持多种语言的识别,在Windows和Linux上都有良好的支持. 创建工程 创建一个C#的控制台工程 添加System ...

  5. C语言的基础输入输出

    首先来整理一下各个数据类型的输入输出格式: 1.char %c 2.int/short int %d 3.long int %ld 4.long long int %lld 5.float %f 6. ...

  6. 《算法导论》——顺序统计RandomizedSelect

    RandomizedSelect.h: #include <stdlib.h> namespace dksl { /* *交换 */ void Swap(int* numArray,int ...

  7. leetcode94

    class Solution { public: vector<int> V; void inOrder(TreeNode* node) { if (node != NULL) { if ...

  8. vue安装搭建

    title: vue安装搭建 date: 2018-04-21 14:00:03 tags: [vue] --- 安装 首先安装nodejs 直接官网下载最新版本http://nodejs.cn/do ...

  9. Mybatis中DAO层接口没有写实现类,Mapper中的方法和DAO接口方法是怎么绑定到一起的,其内部是怎么实现的

    其实也就是通过接口名与mapper的id绑定在一起(即相同),通过SQL去写实现类,返回数据.

  10. MySQL的or/in/union与索引优化

    转载自:MySQL的or/in/union与索引优化 https://blog.csdn.net/zhangweiwei2020/article/details/80005590 假设订单业务表结构为 ...