【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>
简单参数验证
使用spring mvc,可以使用默认提供的注解进行参数验证,下面我们用一个简单的示例列进行说明 实体类Passenger中的NotEmpty要加在field上,所以要使用@get:NotEmpty
import java.time.LocalDateTime
import javax.validation.constraints.NotEmpty
data class Passenger(val id: Int,
//较验参数非空字符串
@get:NotEmpty(message = "用户名不能为空")
val name: String,
var birthday: LocalDateTime
)
添加一个CommonResult来返回操作状态
data class CommonResult<T>(
var data: T?,
var succes: Boolean,
var msg: String
){
constructor():this(null,false,"")
}
Action上要使用@Valid启用验证,否则是不生效的,下面这段我们没有加,就会不生效
@PostMapping("p/add")
fun addPassenger(@RequestBody p:Passenger):CommonResult<Any>{
return CommonResult(null,true,"添加成功")
}
我们post一个json
{"id":1,"name":"","birthday":"2018-08-09T12:33:22.123"}
发现返回了添加成功,确实没有生效
{"data":null,"succes":true,"msg":"添加成功"}
下面我们加上@Valid
@PostMapping("p/add")
fun addPassenger(@Valid @RequestBody p:Passenger):CommonResult<Any>{
return CommonResult(null,true,"添加成功")
}
再次post,发现确实生效了,返回了验证失败
{
"timestamp": "2018-10-25T06:44:31.196+0000",
"status": 400,
"error": "Bad Request",
"errors": [{
"codes": ["NotEmpty.passenger.name", "NotEmpty.name", "NotEmpty.java.lang.String", "NotEmpty"],
"arguments": [{
"codes": ["passenger.name", "name"],
"arguments": null,
"defaultMessage": "name",
"code": "name"
}],
"defaultMessage": "用户名不能为空",
"objectName": "passenger",
"field": "name",
"rejectedValue": "",
"bindingFailure": false,
"code": "NotEmpty"
}],
"message": "Validation failed for object='passenger'. Error count: 1",
"path": "/p/add"
}
来源:oschina
链接:https://my.oschina.net/u/1865350/blog/2252381