标签:get org turn 绑定 import 实体 framework private auth
springboot 验证 默认使用的是hibernate validator ,不用额外增加引用包,springboot已经内置包含。
1)定义接收参数实体
package com.study.valid_demo.vo; import javax.validation.constraints.AssertFalse; import javax.validation.constraints.Pattern; import org.hibernate.validator.constraints.NotBlank; /** * 接收客户端信息载体 * * @author Administrator * */ public class RegisterVO { @NotBlank(message = "用户名不能为空") private String userName; @NotBlank(message = "年龄不能为空") @Pattern(regexp = "^[0-9]{1,2}$", message = "年龄不正确") private String age; @AssertFalse(message = "必须为false") private Boolean isFalse; /** * 如果是空,则不校验,如果不为空,则校验 */ @Pattern(regexp = "^[0-9]{4}-[0-9]{2}-[0-9]{2}$", message = "出生日期格式不正确") private String birthday; public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public Boolean getIsFalse() { return isFalse; } public void setIsFalse(Boolean isFalse) { this.isFalse = isFalse; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } }
2.定义controller
package com.study.valid_demo; import javax.validation.Valid; import org.springframework.validation.BindingResult; import org.springframework.validation.ObjectError; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.study.valid_demo.vo.RegisterVO; @RestController @RequestMapping("/index") public class IndexController { @RequestMapping("/register") @ResponseBody public String register(@RequestBody @Valid RegisterVO register, BindingResult result) { // 使用BindingResult 时,验证错误需要自己处理。应用程序程序正常返回 if (result.hasErrors()) { for (ObjectError error : result.getAllErrors()) { System.out.println(error.getDefaultMessage()); } } return register.getUserName(); } @RequestMapping("/register2") @ResponseBody public String register(@RequestBody @Valid RegisterVO register) { // 不使用ResultBind时,在spring验证绑定时报400 Badrequest错误,并提示错误详细信息 return register.getUserName(); } }
SpringBoot 参数检查 Controller中检查参数是否合法
标签:get org turn 绑定 import 实体 framework private auth
原文地址:https://www.cnblogs.com/liuxm2017/p/9629842.html