场景1: 验证VO字段
场景2:一个Bean ,需要在不同情况下分别做分组验证
场景3:springboot , 统一验证异常处理(需要在不同情况下分别做分组验证)
场景1: 验证VO字段
Bean:
@Data @Document(collection = "booking") public class Booking implements Serializable { private static final long serialVersionUID = 4648928973495587158L; private String businessType; @Id private String id; @NotBlank(message = "bookingNo can't be blank!") private String bookingNo; private Date bookingDateGMT; private Date bookingDateLoc;}
Controller :
@PostMapping("/insert") public Map<String, Object> insert(@Valid Booking booking, BindingResult bindingResult) { Map<String, Object> map = new HashMap<String, Object>(); if (bindingResult.hasErrors()) { List<ObjectError> errorList = bindingResult.getAllErrors(); List<String> mesList=new ArrayList<String>(); for (int i = 0; i < errorList.size(); i++) { mesList.add(errorList.get(i).getDefaultMessage()); } map.put("status", false); map.put("error", mesList); } else { map.put("status", true); map.put("msg", "添加成功"); } return map; }
or
public JSONObject saveOrUpdate(@RequestBody @Valid ServerDO server, BindingResult bindingResult) throws Exception { if(bindingResult.hasErrors()) { List<String> msg = bindingResult.getFieldErrors().stream().map(err->err.getDefaultMessage()).collect(Collectors.toList()); return ResponseUtil.getResult(ResponseCode.VALIDATION_ERROR.getCode(), ResponseCode.VALIDATION_ERROR.getMessage(), msg); } ServerDO solverDO = serverService.saveOrUpdate(server); return ResponseUtil.getResult(ResponseCode.SUCCESS.getCode(),ResponseCode.SUCCESS.getMessage(),solverDO); }
场景2:一个Bean ,需要在不同情况下分别做分组验证
1.依赖:springboot 已经集成
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
2.定义一个bean (验证对象)
import javax.validation.constraints.NotEmpty; import lombok.Getter; import lombok.Setter; import lombok.ToString; @Getter @Setter @ToString public class XiaoMIEntry { @NotEmpty(groups={AgroupMI2.class,AgroupMI.class},message="name can't be null") private String name; private Double price; @NotEmpty(groups={AgroupMI.class},message="color can't be null") private String color; public XiaoMIEntry(@NotEmpty(groups = AgroupMI2.class, message = "name can't be null") String name, Double price, @NotEmpty(groups = AgroupMI.class, message = "color can't be null") String color) { super(); this.name = name; this.price = price; this.color = color; } public XiaoMIEntry() { super(); } }
3.定义分组(仅仅是一个接口,需要extends javax.validation.groups.Default 仅仅只是标识)
分组:1:
import javax.validation.groups.Default; public interface AgroupMI extends Default{ }
分组:2:
import javax.validation.groups.Default; public interface AgroupMI2 extends Default{ }
验证方法:工具类;
import java.util.Set; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @ClassName: BeanValidationUtils * @Description: * @Author: Sea * @Date: 14 Sep 2018 11:24:49 AM * @Copyright: 2018 Sea All rights reserved. */ public class BeanValidationUtils { private static final Logger logger = LoggerFactory.getLogger(BeanValidationUtils.class); /** * * @param obj * @return */ public static String getBeanValidate(Object obj) { StringBuilder validationMessage = new StringBuilder(); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> violations = validator.validate(obj); for (ConstraintViolation<Object> violation : violations) { if(violation.getMessage() != null && !"".equals(violation.getMessage())) { validationMessage.append("<p>"+violation.getMessage()+" ;</p>"); } } return validationMessage.toString(); } /** * * @param obj:需要验证的 bean * @param group :需要验证的分组 * @return */ public static String getBeanValidateByGroup(Object obj,Class<?> group) { StringBuilder validationMessage = new StringBuilder(); ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); Set<ConstraintViolation<Object>> violations = validator.validate(obj,group); for (ConstraintViolation<Object> violation : violations) { if(violation.getMessage() != null && !"".equals(violation.getMessage())) { validationMessage.append("<p>"+violation.getMessage()+" ;</p>"); } } return validationMessage.toString(); } }
test :
import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import org.junit.runner.RunWith; @RunWith(SpringRunner.class) @SpringBootTest public class ValitionByGrouptest { @Test public void testgroup1() throws Exception { XiaoMIEntry xiaoMIEntry = new XiaoMIEntry(null, 1.2, null); String beanValidateByGroup = BeanValidationUtils.getBeanValidateByGroup(xiaoMIEntry, AgroupMI.class); System.out.println("###############"); System.out.println(beanValidateByGroup); System.err.println("######################"); } @Test public void testgroup2() throws Exception { XiaoMIEntry xiaoMIEntry = new XiaoMIEntry(null, 1.2, null); String beanValidateByGroup = BeanValidationUtils.getBeanValidateByGroup(xiaoMIEntry, AgroupMI2.class); System.out.println("###############"); System.out.println(beanValidateByGroup); System.err.println("######################"); }