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

一、包结构和主要文件

二、代码

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. zabbix之 自动发现磁盘io util 监控

    一.iostat Zabbix并没有提供模板来监控磁盘的IO性能,所以我们需要自己来创建一个.iostat主要用于监控系统设备的IO负载情况,iostat首次运行时显示自系统启动开始的各项统计信息,之 ...

  2. Java面试题 OOAD & UML+XML+SQL+JDBC & Hibernate

    二.OOA/D 与UML 部分:(共6 题:基础2 道,中等难度4 道) 96.UML 是什么?常用的几种图?[基础] 答:UML 是标准建模语言:常用图包括:用例图,静态图(包括类图.对象图和包图) ...

  3. laravel框架容器管理

    来自http://www.cnblogs.com/chy1000/p/7072936.html 本文面向php语言的laravel框架的用户,介绍一些laravel框架里面容器管理方面的使用要点.文章 ...

  4. 协议并发测试工具 BoHexTest

    BoHexTest V1.0.3 1.添加连接LOG打印2.优化代理及并发策略 大小: 1074688 字节修改时间: 2017年10月3日, 10:24:26MD5: EBAE5A17F7F5ED0 ...

  5. 20175311 2018-2019-2 《Java程序设计》第1周学习总结

    教材学习内容总结 第一周我们主要尝试了怎么安装各种以后可能需要用到的软件,根据老师提供的博客教程进行自主学习安装软件,然后编写一些简单的语言程序. 教材学习中的问题和解决过程 问题1:在学习过程中主要 ...

  6. auth系统与类视图

    用户 权限 密码哈希系统 表单视图工具 密码强度检查   第三方或自定义 限制登录尝试 第三方验证     (qq,微信,微博登录) 对象级权限 auth    user用户表   group分组表 ...

  7. Linux下安装MySQL----来自简书(挺好的)

    来自简书的: https://www.jianshu.com/p/f4a98a905011 注: 1. 下载方式: 可以使用命令下载: wget http://downloads.mysql.com/ ...

  8. PUSU 拆分后发货和开票的时间节点问题

    项目做到现在业务突然说流程要变,心中顿时无数个草草草掠过.这公司业务也真是够奇葩了,一天一个样.原来流程是由PU把产品生产完后就发给SU,由SU再来决定什么时候对客户和开票.而现在马上要上线了,突然冒 ...

  9. 模拟SQL用户 EXECUTE AS USER

    EXECUTE AS USER= @domain SELECT SUSER_NAME(), USER_NAME(); REVERT 以下语句可以模拟SQL用户,具体使用场景自行脑补.

  10. SYSAUX表空间清理

    最近zabbix告警某业务sysaux表空间使用率超过95%,使用sql查看sysaux表空间设置了32G,32G的表空间竟然使用了95%.一般来讲除开业务数据存放的表空间,DBA要着重关注SYSTE ...