spring mvc controller中的参数验证机制(二)
这里我们介绍以下自定义的校验器的简单的使用示例
一、包结构和主要文件

二、代码
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中的参数验证机制(二)的更多相关文章
- spring mvc controller中的参数验证机制(一)
一.验证用到的注解 @Valid 对传到后台的参数的验证 @BindingResult 配合@Valid使用,验证失败后的返回 二.示例 1.传统方式 @PostMapping public User ...
- Spring MVC Controller中解析GET方式的中文参数会乱码的问题(tomcat如何解码)
Spring MVC Controller中解析GET方式的中文参数会乱码的问题 问题描述 在工作上使用突然出现从get获取中文参数乱码(新装机器,tomcat重新下载和配置),查了半天终于找到解决办 ...
- spring mvc controller中获取request head内容
spring mvc controller中获取request head内容: @RequestMapping("/{mlid}/{ptn}/{name}") public Str ...
- Spring MVC Controller中GET方式传过来的中文参数会乱码的问题
Spring MVC controller 这样写法通常意味着访问该请求,GET和POST请求都行,可是经常会遇到,如果碰到参数是中文的,post请求可以,get请求过来就是乱码.如果强行对参数进行了 ...
- spring MVC controller中的方法跳转到另外controller中的某个method的方法
1. 需求背景 需求:spring MVC框架controller间跳转,需重定向.有几种情况:不带参数跳转,带参数拼接url形式跳转,带参数不拼接参数跳转,页面也能显示. 本来以为挺简单的一 ...
- spring mvc Controller中使用@Value无法获取属性值
在使用spring mvc时,实际上是两个spring容器: 1,dispatcher-servlet.xml 是一个,我们的controller就在这里,所以这个里面也需要注入属性文件 org.sp ...
- spring mvc controller中的异常封装
http://abc08010051.iteye.com/blog/2031992 一直以来都在用spring mvc做mvc框架,我使用的不是基于注解的,还是使用的基于xml的,在controlle ...
- 在Spring MVC Controller中注入HttpServletRequest对象会不会造成线程安全的问题
做法: 1.比如我们在Controller的方法中,通常是直接将HttpServletRequest做为参数,而为了方便节省代码,通常会定义为全局变量,然后使用@Autowire注入. 说明: 1.观 ...
- 本版本延续MVC中的统一验证机制~续的这篇文章,本篇主要是对验证基类的扩展和改善(转)
本版本延续MVC中的统一验证机制~续的这篇文章,本篇主要是对验证基类的扩展和改善 namespace Web.Mvc.Extensions { #region 验证基类 /// <summary ...
随机推荐
- Delphi调用大漠插件示例
Delphi XE2 版本调用大漠插件方法:打开Component->Import Component->默认Import a Type Library,点击Next->找到Dm.d ...
- android 使用Retrofit2 RxJava 文件上传
private static void upload(final Context context, final int type, File logFile) { Map<String, Req ...
- 第18课 类型萃取(2)_获取返回值类型的traits
1. 获取可调用对象返回类型 (1)decltype:获取变量或表达式的类型(见第2课) (2)declval及原型 ①原型:template<class T> T&& d ...
- java之try、catch、finally
结论:try和catch相当于程序分支,finally块中不会改变变量的指针(引用地址):和final修饰的变量类似. public class Test { public static AreaRQ ...
- 论文 | YOLO(You Only Look Once)目标检测
论文:You Only Look Once: Unified, Real-Time Object Detection 原文链接:https://arxiv.org/abs/1506.02640 背景介 ...
- 小程序开发------mpvue开发时间轴
亲们支持我的新博客哦==>地址(以后更新会尽量在新博客更新,欢迎大家访问加入我的后宫w) ) 效果展示: 技术栈:mpvue demo==> 代码:
- Windows操作系统的版本
Windows操作系统的版本号一览 操作系统 PlatformID 主版本号 副版本号 Windows95 1 4 0 Windows98 1 4 10 WindowsMe 1 4 90 Window ...
- Java 身份证号码验证
身份证号码验证 1.号码的结构 公民身份号码是特征组合码,由十七位数字本体码和一位校验码组成.排列顺序从左至右依次为:六位数字地址码,八位数字出生日期码,三位数字顺序码和一位数字校验码 2.地址码(前 ...
- 01 Python初识
基础: 1.后缀名是py ATT: 单个文件执行,后缀无所谓 2.两种执行方式 终端 python+文件路径 解释器内部: 直接执行 3.解释器路径: #/usr/bin/env pyth ...
- ActiveMQ(1)---初识ActiveMQ
消息中间件的初步认识 什么是消息中间件? 消息中间件是值利用高效可靠的消息传递机制进行平台无关的数据交流,并基于数据通信来进行分布式系统的集成.通过提供消息传递和消息排队模型,可以在分布式架构下扩展进 ...