版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/yuchao2015/article/details/78695954

@Valid

Spring MVC采用的校验是hibernate-validate,第一步肯定是导包,就忽略了

可使用的校验注解

  1. @NotNull 值不能为空
  2. @Null 值必须为空
  3. @Pattern(regex=) 字符串必须匹配正则表达式
  4. @Size(min=,max=) 集合的元素数量必须在min和max之间
  5. @CreditNumber(ignoreNonDigitCharacters=) 字符串必须是信用卡号(按美国的标准验证)
  6. @Email 字符串必须是Email地址
  7. @Length(min=,max=) 检查字符串的长度
  8. @NotBlank 字符串必须有字符
  9. @Range(min=,max=) 数字必须大于min,小于等于max
  10. @SafeHtml 字符串是安全的html
  11. @URL 字符串是合法的URL
  12. @AssertFalse 值必须是false
  13. @AssertTrue 值必须是true
  14. @DecimalMax(value,inclusive=) 值必须小于等于(inclusive=true)/小于(inclusive=false) value属性指定的值,可以注解在字符串类型的属性上
  15. @DecimalMin(value,inclusive=) 值必须大于等于(inclusive=true)/大于(inclusive=false) value属性指定的值,可以注解在字符串类型的
  16. 属性上
  17. @Digits(integer=,fraction=) 数字格式检查,integer指定整数部分的最大长度,fraction指定小数部分的最大长度
  18. @Future 值必须是未来的日志
  19. @Past 值必须是过去的日期
  20. @Max(value=) 值必须小于等于value指定的值,不能注视在字符串类型的属性上
  21. @Min(value=) 值必须大于等于value指定的值,不能注视在字符串类型的属性上

简单的校验

用法,首先定义实体

  1. public class User {
  2. private String id;
  3. private String username;
  4. @NotBlank(message = "密码不能为空")
  5. private String password;
  6. @Past(message = "生日必须是过去的时间")
  7. private Date birthday;
  8. //getter and setter
  9. }

控制层实现:

  1. @PutMapping("/{id:\\d+}")
  2. public User update(@Valid @RequestBody User user, BindingResult errors) {
  3. if(errors.hasErrors()){
  4. //errors.getAllErrors().stream().forEach( error -> System.out.println(error.getDefaultMessage()));
  5. errors.getAllErrors().stream().forEach( error ->{
  6. FieldError fieldError = (FieldError)error;
  7. System.out.println(fieldError.getField()+":"+fieldError.getDefaultMessage());
  8. });
  9. }
  10. System.out.println(user.getId());
  11. System.out.println(user.getUsername());
  12. System.out.println(user.getPassword());
  13. System.out.println(user.getBirthday());
  14. user.setId("1");
  15. return user;
  16. }

ok,错误信息就会打印出来,就可以做自己的逻辑处理了

自定义校验器校验

  1. /**
  2. * 自定义的校验器
  3. * Created by xingyuchao on 2017/12/2.
  4. */
  5. @Target({ElementType.METHOD, ElementType.FIELD})
  6. @Retention(RetentionPolicy.RUNTIME)
  7. @Constraint(validatedBy = MyConstraintValidator.class)
  8. public @interface MyConstraint {
  9. String message();
  10. Class<?>[] groups() default { };
  11. Class<? extends Payload>[] payload() default { };
  12. String field() default "";
  13. }

上面那三个属性是必须的

完成校验逻辑,需要注意的是实现了ConstraintValidator的类已经在spring容器中了,因此可以使用注入其它类了
  1. public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {
  2. @Autowired
  3. private HelloService helloService;
  4. @Override
  5. public void initialize(MyConstraint constraintAnnotation) {
  6. System.out.println("my validator init");
  7. }
  8. @Override
  9. public boolean isValid(Object value, ConstraintValidatorContext context) {
  10. helloService.greeting("tom");
  11. System.out.println(value);
  12. return false; //返回true则校验通过,false校验不通过
  13. }
  14. }

使用

  1. private String id;
  2. @MyConstraint(message = "这是一个校验测试")
  3. private String username;
  4. @NotBlank(message = "密码不能为空")
  5. private String password;
  6. @Past(message = "生日必须是过去的时间")
  7. private Date birthday;

@JsonView

@JsonView可以过滤序列化对象的字段属性,可以使你有选择的序列化对象。

使用步骤:
  1. 使用接口来声明多个视图
  2. 在值对象的get方法上指定视图
  3. 在controller方法上指定视图
  1. public class User {
  2. public interface UserSimpleView {};
  3. public interface UserDetailView extends UserSimpleView {};
  4. private String username;
  5. private String password;
  6. @JsonView(UserSimpleView.class)
  7. public String getUsername() { return username; }
  8. public void setUsername(String username) { this.username = username;}
  9. @JsonView(UserDetailView.class)
  10. public String getPassword() {return password;}
  11. public void setPassword(String password) {this.password = password;}
  12. }
  1. @RestController
  2. @RequestMapping("/user")
  3. public class UserController {
  4. @GetMapping
  5. @JsonView(User.UserSimpleView.class)
  6. public List<User> query(UserQueryCondition condition,
  7. @PageableDefault(page = 2, size = 17, sort = "username",direction= Sort.Direction.DESC) Pageable pageable){
  8. System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE)); //打印toString
  9. System.out.println(pageable.getPageSize());
  10. System.out.println(pageable.getPageNumber());
  11. System.out.println(pageable.getSort());
  12. List<User> userList = new ArrayList<>();
  13. userList.add(new User());
  14. userList.add(new User());
  15. userList.add(new User());
  16. return userList;
  17. }
  18. //{id:\\d+} 表示只能是数字
  19. @GetMapping("/{id:\\d+}")
  20. @JsonView(User.UserDetailView.class)
  21. public User getInfo( @PathVariable String id) {
  22. // throw new RuntimeException("user not exist");
  23. System.out.println("进入getInfo服务");
  24. User user = new User();
  25. user.setUsername("tom");
  26. return user;
  27. }
  28. }

@JsonSerialize

此注解用于属性或者getter方法上,用于在序列化时嵌入我们自定义的代码,比如序列化一个double时在其后面限制两位小数点。
因为在java中日期时期的时间戳是ms,我现在需要将ms转换为s,也就是除以1k
  1. public class Date2LongSerializer extends JsonSerializer<Date> {
  2. @Override
  3. public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
  4. jsonGenerator.writeNumber(date.getTime() / 1000);
  5. }
  6. }
使用:
  1. private String id;
  2. @MyConstraint(message = "这是一个校验测试")
  3. private String username;
  4. @NotBlank(message = "密码不能为空")
  5. private String password;
  6. @JsonSerialize(using = Date2LongSerializer.class)
  7. @Past(message = "生日必须是过去的时间")
  8. private Date birthday;

这样就完成了时间戳13位到10位的转换

@JsonIgnore、@JsonIgnoreProperties

@JsonIgnoreProperties:此注解是类注解,作用是json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都受影响。@JsonIgnore:此注解用于属性或者方法上(最好是属性上),作用和上面的@JsonIgnoreProperties一样。
都是用于Json转换忽略空字段,也可以通过其它方式控制
第一种局部控制:


第二种:全局控制,我这用的springboot


还有其它json的相关注解,就不列举了,可以参考:https://www.cnblogs.com/guijl/p/3855329.html
        </div></div>

Spring MVC注解@Valid、@JsonSerialize、@JsonView等相关推荐

  1. java注解式开发_JAVA语言之Spring MVC注解式开发使用详解[Java代码]

    本文主要向大家介绍了JAVA语言的Spring MVC注解式开发使用详解,通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助. MVC注解式开发即处理器基于注解的类开发, 对于每一个定义的处 ...

  2. spring mvc(注解)上传文件的简单例子

    spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方 1.form的enctype="multipart/form-data" 这个是上传文件必须的 2.appl ...

  3. 【spring学习笔记】(二)Spring MVC注解配置 参数转换注解@RequestMapping@RequestParam、@PathVariable@MatrixVariable

    @TOC 介绍 在Spring MVC项目中,<\context:component-scan>配置标签还会开启@Request-Mapping.@GetMapping等映射注解功能(也就 ...

  4. Spring MVC注解故障追踪记

    2019独角兽企业重金招聘Python工程师标准>>> Spring MVC是美团点评很多团队使用的Web框架.在基于Spring MVC的项目里,注解的使用几乎遍布在项目中的各个模 ...

  5. Spring MVC注解、标签库、国际化

    本篇文章主要介绍自己在学习Spring MVC常用注解.标签库.国际化遇到的一些问题,分享给大家,希望对你有所帮助. 问题一:指定扫描包的位置 应该将所有控制器类都放在基本包下,并且指定该扫描包,避免 ...

  6. Http请求中Content-Type讲解以及在Spring MVC注解中produce和consumes配置详解

    转载自https://blog.csdn.net/shinebar/article/details/54408020 引言: 在Http请求中,我们每天都在使用Content-type来指定不同格式的 ...

  7. spring mvc注解笔记

    1.@Controller @Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象.分发处理器将会扫描使用了该注解的类的方法, 并检测该方法是 ...

  8. Spring mvc 注解@ResponseBody 返回内容编码问题

    @ResponseBody 在@Controller 类方法中能够让字符串直接返回内容. 其返回处理的类是org.springframework.http.converter.StringHttpMe ...

  9. Spring mvc注解方式使用事务回滚

    项目名:1ma1ma jdbc.xml <bean  id="dataSource" class="org.apache.commons.dbcp.BasicDat ...

最新文章

  1. 大数据实战之环境搭建(八)
  2. 合并html文件工具,整合 DevTools 和 Chrome
  3. 网页魔法菜单(使用说明)
  4. python算法与数据结构-单链表
  5. java转scala
  6. 计算机视觉中的Transformer的最新进展!
  7. 没有智能安防 智能家居只是一座空中楼阁
  8. 《万物互联》——2.3 理解智能设备
  9. 判断一个数是否为素数 java_java中如何判断一个数是否是素数(质数)
  10. Ubuntu16.04 ext4格式硬盘挂载普通用户权限控制
  11. python中seek函数_Python seek()函数
  12. js中的四种常用数组排序方法(冒泡、选择、插入、快排)及sort排序
  13. 解决css修改但是没有反应
  14. web前端程序员职位介绍
  15. python3中文件的读与写
  16. 如何在MathType中输入摄氏度符号
  17. Java/Swing 图形界面范例
  18. Maven系列第五讲 私服讲解
  19. office文档管理服务器编辑,_卓正软件 - PageOffice官方网站 - 在线编辑Word、Excel的Office文档控件...
  20. 兼容PD快充5V-12V高压给两节串联8.4V锂电池1A充电芯片电路图

热门文章

  1. 【数据库系统】数据库系统概论====第六章 关系数据库理论
  2. Python中set的用法
  3. 关于__irq的使用
  4. php中var_dump是什么意思?
  5. 高斯消去法python(源码)
  6. BR8041A02 串口烧录接线说明
  7. UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
  8. 中美人工智能技术差距太大 不可急着商业化
  9. android聊天会话代码,Android 即时聊天-融云IM集成。
  10. Scrapy的简介和安装