spring参数校验之validation的⾃定义注解validation的⾃定义注解
@Data
public class ValidaUr {
private final String reg = "^((http|https)://)[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]";
# @CheckUrl为我的⾃定义注解,详见如下
@CheckUrl(regexp = reg, message = "contractCallBackUrl地址⾮法")
private String contractCallBackUrl;
@CheckUrl(regexp = reg, notEmpty = fal, message = "archivesCallBackUrl地址⾮法地址⾮法地址⾮法")
private String archivesCallBackUrl;
public ValidaUr(String contractCallBackUrl, String archivesCallBackUrl) {
this.archivesCallBackUrl = archivesCallBackUrl;
}
}
@RestController
@RequestMapping("/valida")
public class ValidaController {
@RequestMapping("/validaParam")
public String validaParam(@Validated @RequestBody ValidaUr ur, BindingResult result) throws Exception{
if (result.hasFieldErrors()) {
String errorInfo = ValidationUtils.operateBindingResult(result);
System.out.println(errorInfo);
// return errorInfo;
}
System.out.println("请求参数::"+JSONString(ur));
return "success";
}
}
@RunWith(SpringRunner.class)
@SpringBootTest
@WebAppConfiguration
@AutoConfigureMockMvc
public class ValidaControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void validaParam(){
List<String> list = Arrays.asList("1212", "1212", "1212", "1212", "1212", "1212", "1212", "1212", "1212", "1212", "1212", "1212"); ValidaUr validaUr = new ValidaUr("","");
try {
mockMvc.perform(post("/valida/validaParam")//请求地址使⽤post⽅式请求
.JSONString(validaUr))
.contentType(MediaType.APPLICATION_JSON_VALUE))//媒体类型为JSON
// .andExpect(status().isOk());//返回状态为200
.andDo(print());// 打印请求和响应的详情
} catch (Exception e) {
e.printStackTrace();
}
}
}
1、单元测试类中的参数都设置为 “” 空字符串
问题:两个参数都为空使⽤的是同⼀个参数校验注解为什么只提⽰⼀个
原因如下:在编写⾃定义注解时,甚⾄了⼀个开关,fal为空字符 “” 时不校验, true时则校验
⾃定义注解如下
@Constraint(validatedBy = CheckUrlValidator.class) CheckUrlValidator 为注解的校验类
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
/**
* @author zsg
*/
@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = CheckUrlValidator.class)
public @interface CheckUrl {
String regexp();
boolean notEmpty() default true; # 空字符是否校验,默认校验
String message() default "路径地址错误";
# 以下两个为必须校验默认分组
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
实现接⼝:ConstraintValidator<A extends Annotation, T>
import org.springframework.util.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import Pattern;
/**
* FileName: ample.demo.utils.CheckUrlValidator
*
* @author: zsg
*/
public class CheckUrlValidator implements ConstraintValidator<CheckUrl, String> {
private String regexp;
private boolean notEmpty;
@Override
public void initialize(CheckUrl constraintAnnotation) {
}
@Override
public boolean isValid(String url, ConstraintValidatorContext constraintValidatorContext) { if(StringUtils.isEmpty(url)){
return !notEmpty;
}
Pattern pattern = pile(regexp);
return pattern.matcher(url).matches();
}
}
1、正常参数请求如下