Spring MVC注解@Valid、@JsonSerialize、@JsonView等
@Valid
Spring MVC采用的校验是hibernate-validate,第一步肯定是导包,就忽略了
可使用的校验注解
- @NotNull 值不能为空
- @Null 值必须为空
- @Pattern(regex=) 字符串必须匹配正则表达式
- @Size(min=,max=) 集合的元素数量必须在min和max之间
- @CreditNumber(ignoreNonDigitCharacters=) 字符串必须是信用卡号(按美国的标准验证)
- @Email 字符串必须是Email地址
- @Length(min=,max=) 检查字符串的长度
- @NotBlank 字符串必须有字符
- @Range(min=,max=) 数字必须大于min,小于等于max
- @SafeHtml 字符串是安全的html
- @URL 字符串是合法的URL
- @AssertFalse 值必须是false
- @AssertTrue 值必须是true
- @DecimalMax(value,inclusive=) 值必须小于等于(inclusive=true)/小于(inclusive=false) value属性指定的值,可以注解在字符串类型的属性上
- @DecimalMin(value,inclusive=) 值必须大于等于(inclusive=true)/大于(inclusive=false) value属性指定的值,可以注解在字符串类型的
- 属性上
- @Digits(integer=,fraction=) 数字格式检查,integer指定整数部分的最大长度,fraction指定小数部分的最大长度
- @Future 值必须是未来的日志
- @Past 值必须是过去的日期
- @Max(value=) 值必须小于等于value指定的值,不能注视在字符串类型的属性上
- @Min(value=) 值必须大于等于value指定的值,不能注视在字符串类型的属性上
简单的校验
用法,首先定义实体
- public class User {
- private String id;
- private String username;
- @NotBlank(message = "密码不能为空")
- private String password;
- @Past(message = "生日必须是过去的时间")
- private Date birthday;
- //getter and setter
- }
控制层实现:
- @PutMapping("/{id:\\d+}")
- public User update(@Valid @RequestBody User user, BindingResult errors) {
- if(errors.hasErrors()){
- //errors.getAllErrors().stream().forEach( error -> System.out.println(error.getDefaultMessage()));
- errors.getAllErrors().stream().forEach( error ->{
- FieldError fieldError = (FieldError)error;
- System.out.println(fieldError.getField()+":"+fieldError.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;
- }
ok,错误信息就会打印出来,就可以做自己的逻辑处理了
自定义校验器校验
- /**
- * 自定义的校验器
- * Created by xingyuchao on 2017/12/2.
- */
- @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 { };
- String field() default "";
- }
上面那三个属性是必须的
完成校验逻辑,需要注意的是实现了ConstraintValidator的类已经在spring容器中了,因此可以使用注入其它类了
- public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {
- @Autowired
- private HelloService helloService;
- @Override
- public void initialize(MyConstraint constraintAnnotation) {
- System.out.println("my validator init");
- }
- @Override
- public boolean isValid(Object value, ConstraintValidatorContext context) {
- helloService.greeting("tom");
- System.out.println(value);
- return false; //返回true则校验通过,false校验不通过
- }
- }
使用
- private String id;
- @MyConstraint(message = "这是一个校验测试")
- private String username;
- @NotBlank(message = "密码不能为空")
- private String password;
- @Past(message = "生日必须是过去的时间")
- private Date birthday;
@JsonView
@JsonView可以过滤序列化对象的字段属性,可以使你有选择的序列化对象。
- 使用接口来声明多个视图
- 在值对象的get方法上指定视图
- 在controller方法上指定视图
- public class User {
- public interface UserSimpleView {};
- public interface UserDetailView extends UserSimpleView {};
- private String username;
- private String password;
- @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;}
- }
- @RestController
- @RequestMapping("/user")
- public class UserController {
- @GetMapping
- @JsonView(User.UserSimpleView.class)
- public List<User> query(UserQueryCondition condition,
- @PageableDefault(page = 2, size = 17, sort = "username",direction= Sort.Direction.DESC) Pageable pageable){
- System.out.println(ReflectionToStringBuilder.toString(condition, ToStringStyle.MULTI_LINE_STYLE)); //打印toString
- System.out.println(pageable.getPageSize());
- System.out.println(pageable.getPageNumber());
- System.out.println(pageable.getSort());
- List<User> userList = new ArrayList<>();
- userList.add(new User());
- userList.add(new User());
- userList.add(new User());
- return userList;
- }
- //{id:\\d+} 表示只能是数字
- @GetMapping("/{id:\\d+}")
- @JsonView(User.UserDetailView.class)
- public User getInfo( @PathVariable String id) {
- // throw new RuntimeException("user not exist");
- System.out.println("进入getInfo服务");
- User user = new User();
- user.setUsername("tom");
- return user;
- }
- }
@JsonSerialize
此注解用于属性或者getter方法上,用于在序列化时嵌入我们自定义的代码,比如序列化一个double时在其后面限制两位小数点。
因为在java中日期时期的时间戳是ms,我现在需要将ms转换为s,也就是除以1k
- public class Date2LongSerializer extends JsonSerializer<Date> {
- @Override
- public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
- jsonGenerator.writeNumber(date.getTime() / 1000);
- }
- }
使用:
- private String id;
- @MyConstraint(message = "这是一个校验测试")
- private String username;
- @NotBlank(message = "密码不能为空")
- private String password;
- @JsonSerialize(using = Date2LongSerializer.class)
- @Past(message = "生日必须是过去的时间")
- private Date birthday;
这样就完成了时间戳13位到10位的转换
@JsonIgnore、@JsonIgnoreProperties
都是用于Json转换忽略空字段,也可以通过其它方式控制
第一种局部控制:
第二种:全局控制,我这用的springboot
还有其它json的相关注解,就不列举了,可以参考:https://www.cnblogs.com/guijl/p/3855329.html
</div></div>
Spring MVC注解@Valid、@JsonSerialize、@JsonView等相关推荐
- java注解式开发_JAVA语言之Spring MVC注解式开发使用详解[Java代码]
本文主要向大家介绍了JAVA语言的Spring MVC注解式开发使用详解,通过具体的内容向大家展示,希望对大家学习JAVA语言有所帮助. MVC注解式开发即处理器基于注解的类开发, 对于每一个定义的处 ...
- spring mvc(注解)上传文件的简单例子
spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方 1.form的enctype="multipart/form-data" 这个是上传文件必须的 2.appl ...
- 【spring学习笔记】(二)Spring MVC注解配置 参数转换注解@RequestMapping@RequestParam、@PathVariable@MatrixVariable
@TOC 介绍 在Spring MVC项目中,<\context:component-scan>配置标签还会开启@Request-Mapping.@GetMapping等映射注解功能(也就 ...
- Spring MVC注解故障追踪记
2019独角兽企业重金招聘Python工程师标准>>> Spring MVC是美团点评很多团队使用的Web框架.在基于Spring MVC的项目里,注解的使用几乎遍布在项目中的各个模 ...
- Spring MVC注解、标签库、国际化
本篇文章主要介绍自己在学习Spring MVC常用注解.标签库.国际化遇到的一些问题,分享给大家,希望对你有所帮助. 问题一:指定扫描包的位置 应该将所有控制器类都放在基本包下,并且指定该扫描包,避免 ...
- Http请求中Content-Type讲解以及在Spring MVC注解中produce和consumes配置详解
转载自https://blog.csdn.net/shinebar/article/details/54408020 引言: 在Http请求中,我们每天都在使用Content-type来指定不同格式的 ...
- spring mvc注解笔记
1.@Controller @Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象.分发处理器将会扫描使用了该注解的类的方法, 并检测该方法是 ...
- Spring mvc 注解@ResponseBody 返回内容编码问题
@ResponseBody 在@Controller 类方法中能够让字符串直接返回内容. 其返回处理的类是org.springframework.http.converter.StringHttpMe ...
- Spring mvc注解方式使用事务回滚
项目名:1ma1ma jdbc.xml <bean id="dataSource" class="org.apache.commons.dbcp.BasicDat ...
最新文章
- 大数据实战之环境搭建(八)
- 合并html文件工具,整合 DevTools 和 Chrome
- 网页魔法菜单(使用说明)
- python算法与数据结构-单链表
- java转scala
- 计算机视觉中的Transformer的最新进展!
- 没有智能安防 智能家居只是一座空中楼阁
- 《万物互联》——2.3 理解智能设备
- 判断一个数是否为素数 java_java中如何判断一个数是否是素数(质数)
- Ubuntu16.04 ext4格式硬盘挂载普通用户权限控制
- python中seek函数_Python seek()函数
- js中的四种常用数组排序方法(冒泡、选择、插入、快排)及sort排序
- 解决css修改但是没有反应
- web前端程序员职位介绍
- python3中文件的读与写
- 如何在MathType中输入摄氏度符号
- Java/Swing 图形界面范例
- Maven系列第五讲 私服讲解
- office文档管理服务器编辑,_卓正软件 - PageOffice官方网站 - 在线编辑Word、Excel的Office文档控件...
- 兼容PD快充5V-12V高压给两节串联8.4V锂电池1A充电芯片电路图
热门文章
- 【数据库系统】数据库系统概论====第六章 关系数据库理论
- Python中set的用法
- 关于__irq的使用
- php中var_dump是什么意思?
- 高斯消去法python(源码)
- BR8041A02 串口烧录接线说明
- UnexpectedRollbackException: Transaction rolled back because it has been marked as rollback-only
- 中美人工智能技术差距太大 不可急着商业化
- android聊天会话代码,Android 即时聊天-融云IM集成。
- Scrapy的简介和安装