springboot---->springboot中的校验器(一)
这里面我们简单的学习一下springboot中关于数据格式化的使用。冬天花败,春暖花开,有人离去,有人归来。
springboot中的校验器
我们的测试环境是springboot,对请求的person数据先做转换再校验。
一、我们定义的实体Bean类Person
package com.linux.huhx.learn.converter;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import java.io.Serializable;
/**
* @Author: huhx
* @Date: 2017-12-15 下午 3:30
* @Desc: 实体类
*/
public class Person implements Serializable {
@NotNull(message = "用户名不能为空")
@Size(min = 3, message = "用户名的长度小于3位")
private String username;
private String password;
@Min(value = 18, message = "用户的年龄不能小于18")
private int age;
public Person(String username, String password, int age) {
this.username = username;
this.password = password;
this.age = age;
}
// ..get set
}
二、我们的检验控制器类
package com.linux.huhx.learn.converter;
import com.linux.huhx.exception.MaxRunTimeException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.Valid;
/**
* @Author: huhx
* @Date: 2017-12-15 下午 3:46
* @Desc: 测试springboot中自定义类型转换器
*/
@RestController
@RequestMapping("/converter")
public class PersonConverterAction {
@PostMapping("/person")
public Person convertrStringToPerson(@Valid Person person, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
for (ObjectError error : bindingResult.getAllErrors()) {
throw new MaxRunTimeException(error.getDefaultMessage());
}
}
return person;
}
}
通过postman发送post的请求:http://localhost:9998/converter/person。
返回的数据:
{
"timestamp": 1513336242870,
"status": 500,
"error": "Internal Server Error",
"exception": "com.linux.huhx.exception.MaxRunTimeException",
"message": "用户的年龄不能小于18",
"path": "/converter/person"
}
作者:
huhx
出处: www.cnblogs.com/huhx
格言:你尽力了,才有资格说自己的运气不好。
版权:本文版权归作者huhx和博客园共有,欢迎转载。未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
出处: www.cnblogs.com/huhx
格言:你尽力了,才有资格说自己的运气不好。
版权:本文版权归作者huhx和博客园共有,欢迎转载。未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。