javax.validation.constraints
支持的写法
1 库
class="java" name="code">
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>1.1.0.Final</version>
</dependency>
2 校验字段上添加校验
注解
class Profile{
@NotNull(message = "字段值不能为空")
private String name;
@NotNull
private String sex;
@Max(value = 20,message = "最大长度为20")
private String address;
@NotNull
@Size(max=10,min=5,message = "字段长度要在5-10之间")
private String fileName;
@Pattern(regexp = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$",message = "不满足邮箱正则表达式")
private String email;
@AssertTrue(message = "字段为true才能通过")
private boolean isSave;
@Future(message = "时间在当前时间之后才可以通过")
private Date date;
@Future(message = "生日必须在当前实践之前")
private Date birthday;
@Pattern(regexp = "^(.+)@(.+)$",message = "邮箱的格式不合法")
private String email;
@Size(min = 6,max = 30,message = "地址应该在6-30字符之间")
private String address;
@DecimalMax(value = "100.00",message = "体重有些超标哦")
@DecimalMin(value = "60.00",message = "多吃点饭吧")
private BigDecimal weight;
}
3 在Controller层使用@Validated进行验证
@RequestMapping("file/upload")
public void upload(@RequestPart("files") MultipartFile files, @Validated Profile profile, Errors error) throws IOException {
if(error.hasErrors()){
return;
}
files.transferTo(new File(files.getOriginalFilename()));////保存文件
}
4
自定义bean validation 注解验证 https://www.cnb
logs.com/xiaogangfan/p/5987659.html
optional参考
https://www.runoob.com/java/java8-optional-class.html
java 中
try catch 当抛出
异常的时候 性能大幅下降,没事少用.
- 大小: 111.4 KB