下面列出了怎么用javax.validation.constraints.NotEmpty的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 关键字提醒
* <p>
* 当用户输入关键字一部分时,可以推荐系统中合适的关键字。
*
* @param keyword
* 关键字
* @return 合适的关键字
*/
@GetMapping("helper")
public Object helper(@NotEmpty String keyword, @RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size) {
logger.info("【请求开始】关键字提醒,请求参数,keyword:{}", keyword);
List<DtsKeyword> keywordsList = keywordsService.queryByKeyword(keyword, page, size);
String[] keys = new String[keywordsList.size()];
int index = 0;
for (DtsKeyword key : keywordsList) {
keys[index++] = key.getKeyword();
}
logger.info("【请求结束】关键字提醒,响应结果:{}", JSONObject.toJSONString(keys));
return ResponseUtil.ok(keys);
}
/**
* 刷新缓存
*
* @param cacheItems
*/
public void refreshCache(@NotEmpty List<String> cacheItems) {
List<String> deleteSuccessKeys = new ArrayList<>();
List<String> deleteFailKeys = new ArrayList<>();
for (String cacheItem : cacheItems) {
Set<String> keys = redisTemplate.keys(cacheItem);
for (String key : keys) {
Boolean flag = redisTemplate.delete(key);
if (flag) {
deleteSuccessKeys.add(key);
} else {
deleteFailKeys.add(key);
}
}
}
if (!deleteFailKeys.isEmpty()) {
log.warn("以下的缓存删除失败:", deleteFailKeys);
}
}
/**
* Determine whether a given field or method is annotated to be not nullable.
*
* @param member the field or method to check
* @return whether member is annotated as nullable or not (returns null if not specified: assumption it is nullable then)
*/
protected Boolean isNullable(MemberScope<?, ?> member) {
Boolean result;
if (this.getAnnotationFromFieldOrGetter(member, NotNull.class, NotNull::groups) != null
|| this.getAnnotationFromFieldOrGetter(member, NotBlank.class, NotBlank::groups) != null
|| this.getAnnotationFromFieldOrGetter(member, NotEmpty.class, NotEmpty::groups) != null) {
// field is specifically NOT nullable
result = Boolean.FALSE;
} else if (this.getAnnotationFromFieldOrGetter(member, Null.class, Null::groups) != null) {
// field is specifically null (and thereby nullable)
result = Boolean.TRUE;
} else {
result = null;
}
return result;
}
@POST
public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
@QueryParam("age") @PositiveOrZero int age){
Person p = new Person(name, age);
try (Connection conn = defaultDataSource.getConnection();
PreparedStatement ps = conn.prepareStatement("INSERT INTO people VALUES(?,?,?)")){
ps.setLong(1, p.id);
ps.setString(2, name);
ps.setInt(3, age);
ps.execute();
return p.id;
} catch (SQLException e) {
e.printStackTrace(System.out);
}
throw new InternalServerErrorException("Could not create new person");
}
private void resolveAnnotatedElement(ModelPropertyContext context) {
AnnotatedElement annotated = context.getAnnotatedElement().orNull();
if (annotated == null) {
return;
}
if (AnnotationUtils.findAnnotation(annotated, NotNull.class) != null) {
context.getBuilder().required(true);
} else if (AnnotationUtils.findAnnotation(annotated, NotEmpty.class) != null) {
context.getBuilder().required(true);
} else if (AnnotationUtils.findAnnotation(annotated, NotBlank.class) != null) {
context.getBuilder().required(true);
} else {
ApiModelProperty annotation = AnnotationUtils.findAnnotation(annotated, ApiModelProperty.class);
if (annotation != null && annotation.required()) {
//如果ApiModelProperty上强制要求required为true,则为true
context.getBuilder().required(true);
} else {
context.getBuilder().required(false);
}
}
}
@POST
public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
@QueryParam("age") @PositiveOrZero int age){
Person p = new Person(name, age);
try (Connection conn = defaultDataSource.getConnection();
PreparedStatement ps = conn.prepareStatement("INSERT INTO people VALUES(?,?,?)")){
ps.setLong(1, p.id);
ps.setString(2, name);
ps.setInt(3, age);
ps.execute();
return p.id;
} catch (SQLException e) {
e.printStackTrace(System.out);
}
throw new InternalServerErrorException("Could not create new person");
}
public UserAndPasswordDto(Integer userId, @NotEmpty String username, String fullName, String description, String password) {
this.userId = userId;
this.username = username;
this.fullName = fullName;
this.description = description;
this.password = password;
}
@Override
public boolean grant(@NotEmpty List<Long> roleIds, @NotEmpty List<Long> menuIds) {
// 删除角色配置的菜单集合
roleMenuService.remove(Wrappers.<RoleMenu>update().lambda().in(RoleMenu::getRoleId, roleIds));
// 组装配置
List<RoleMenu> roleMenus = new ArrayList<>();
roleIds.forEach(roleId -> menuIds.forEach(menuId -> {
RoleMenu roleMenu = new RoleMenu();
roleMenu.setRoleId(roleId);
roleMenu.setMenuId(menuId);
roleMenus.add(roleMenu);
}));
// 新增配置
return roleMenuService.saveBatch(roleMenus);
}
/**
* Determine a given array type's minimum number of items.
*
* @param member the field or method to check
* @return specified minimum number of array items (or null)
* @see Size
*/
protected Integer resolveArrayMinItems(MemberScope<?, ?> member) {
if (member.isContainerType()) {
Size sizeAnnotation = this.getAnnotationFromFieldOrGetter(member, Size.class, Size::groups);
if (sizeAnnotation != null && sizeAnnotation.min() > 0) {
// minimum length greater than the default 0 was specified
return sizeAnnotation.min();
}
if (this.getAnnotationFromFieldOrGetter(member, NotEmpty.class, NotEmpty::groups) != null) {
return 1;
}
}
return null;
}
/**
* Determine a given text type's minimum number of characters.
*
* @param member the field or method to check
* @return specified minimum number of characters (or null)
* @see Size
* @see NotEmpty
* @see NotBlank
*/
protected Integer resolveStringMinLength(MemberScope<?, ?> member) {
if (member.getType().isInstanceOf(CharSequence.class)) {
Size sizeAnnotation = this.getAnnotationFromFieldOrGetter(member, Size.class, Size::groups);
if (sizeAnnotation != null && sizeAnnotation.min() > 0) {
// minimum length greater than the default 0 was specified
return sizeAnnotation.min();
}
if (this.getAnnotationFromFieldOrGetter(member, NotEmpty.class, NotEmpty::groups) != null
|| this.getAnnotationFromFieldOrGetter(member, NotBlank.class, NotBlank::groups) != null) {
return 1;
}
}
return null;
}
@POST
public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
@QueryParam("age") @PositiveOrZero int age) {
Person p = new Person(name, age);
personRepo.put(p.id, p);
return p.id;
}
@POST
public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
@QueryParam("age") @PositiveOrZero int age) {
Person p = new Person(name, age);
personRepo.put(p.id, p);
return p.id;
}
@POST
public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
@QueryParam("age") @PositiveOrZero int age) {
Person p = new Person(name, age);
personRepo.put(p.id, p);
return p.id;
}
@POST
public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
@QueryParam("age") @PositiveOrZero int age) {
Person p = new Person(name, age);
personRepo.put(p.id, p);
return p.id;
}
@POST
public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
@QueryParam("age") @PositiveOrZero int age) {
Person p = new Person(name, age);
personRepo.put(p.id, p);
return p.id;
}
/**
* 关键字提醒
* <p>
* 当用户输入关键字一部分时,可以推荐系统中合适的关键字。
*
* @param keyword 关键字
* @return 合适的关键字
*/
@GetMapping("helper")
public Object helper(@NotEmpty String keyword,
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer size) {
List<LitemallKeyword> keywordsList = keywordsService.queryByKeyword(keyword, page, size);
String[] keys = new String[keywordsList.size()];
int index = 0;
for (LitemallKeyword key : keywordsList) {
keys[index++] = key.getKeyword();
}
return ResponseUtil.ok(keys);
}
/**
* 关键字提醒
* <p>
* 当用户输入关键字一部分时,可以推荐系统中合适的关键字。
*
* @param keyword 关键字
* @return 合适的关键字
*/
@GetMapping("helper")
public Object helper(@NotEmpty String keyword,
@RequestParam(defaultValue = "1") Integer page,
@RequestParam(defaultValue = "10") Integer limit) {
List<LitemallKeyword> keywordsList = keywordsService.queryByKeyword(keyword, page, limit);
String[] keys = new String[keywordsList.size()];
int index = 0;
for (LitemallKeyword key : keywordsList) {
keys[index++] = key.getKeyword();
}
return ResponseUtil.ok(keys);
}
@ResponseStatus(HttpStatus.ACCEPTED)
@PostMapping("/events/{type}")
@ResponseBody
EventSaveResult oldAddEvent(
@NotEmpty
@PathVariable String type, @RequestBody Event event) {
event.setIp(getClientIp());
//成功时返回202而不是200,为了兼容早期的一些生产者而不校验ip
event.setType(type);
event.normalizeBody();
Event newEvent = eventService.checkAndSaveEvent(event);
return new EventSaveResult(new EventResult(newEvent.getId()));
}
private static Map<Class<? extends Annotation>, String> initErrorCodeMapping() {
Map<Class<? extends Annotation>, String> codes = new HashMap<>();
// Standard Constraints
codes.put(AssertFalse.class, "shouldBeFalse");
codes.put(AssertTrue.class, "shouldBeTrue");
codes.put(DecimalMax.class, "exceedsMax");
codes.put(DecimalMin.class, "lessThanMin");
codes.put(Digits.class, "tooManyDigits");
codes.put(Email.class, "invalidEmail");
codes.put(Future.class, "shouldBeInFuture");
codes.put(FutureOrPresent.class, "shouldBeInFutureOrPresent");
codes.put(Max.class, "exceedsMax");
codes.put(Min.class, "lessThanMin");
codes.put(Negative.class, "shouldBeNegative");
codes.put(NegativeOrZero.class, "shouldBeNegativeOrZero");
codes.put(NotBlank.class, "shouldNotBeBlank");
codes.put(NotEmpty.class, "shouldNotBeEmpty");
codes.put(NotNull.class, "isRequired");
codes.put(Null.class, "shouldBeMissing");
codes.put(Past.class, "shouldBeInPast");
codes.put(PastOrPresent.class, "shouldBeInPastOrPresent");
codes.put(Pattern.class, "invalidPattern");
codes.put(Positive.class, "shouldBePositive");
codes.put(PositiveOrZero.class, "shouldBePositiveOrZero");
codes.put(Size.class, "invalidSize");
// Hibernate Validator Specific Constraints
codes.put(URL.class, "invalidUrl");
codes.put(UniqueElements.class, "shouldBeUnique");
codes.put(SafeHtml.class, "unsafeHtml");
codes.put(Range.class, "outOfRange");
codes.put(Length.class, "invalidSize");
return codes;
}
/**
* Add notification target objects.
*
* @param toObjectArray
* @return
*/
public GenericNotifyMessage addToObjects(@NotEmpty String... toObjectArray) {
if (!isNull(toObjectArray) && toObjectArray.length > 0) {
for(String s : toObjectArray){
hasTextOf(s,"toObjects");
}
toObjects.addAll(asList(toObjectArray).stream().filter(t -> !isNull(t)).collect(toList()));
}
return this;
}
/**
* ok
* 方法上的@Validated注解,一般用来指定 验证组
*
* @param code
* @return
*/
@GetMapping("/requestParam/get")
@Validated
public String paramGet(@Length(max = 3)
@NotEmpty(message = "不能为空")
@RequestParam(value = "code", required = false) String code) {
return "方法上的@Validated注解,一般用来指定 验证组";
}
@GetMapping("/requestParam/get3")
public String paramGet3(@Validated @NotEmpty(message = "code 不能为空")
@RequestParam(value = "code", required = false) String code,
@NotEmpty(message = "name 不能空")
@RequestParam(value = "name", required = false) String name
) {
return "不能验证";
}
/**
* 不能
*
* @param code
* @return
*/
@GetMapping("/requestParam/get4")
@Valid
public String paramGet4(@NotEmpty(message = "不能为空")
@RequestParam(value = "code", required = false) String code) {
return "不能验证";
}
@GetMapping("/requestParam/get6")
public String paramGet6(@Valid @NotEmpty(message = "code 不能为空")
@RequestParam(value = "code", required = false) String code,
@NotEmpty(message = "name 不能空")
@RequestParam(value = "name", required = false) String name
) {
return "不能验证";
}
private void resolveBeanPropertyDefinition(ModelPropertyContext context) {
BeanPropertyDefinition beanPropertyDefinition = context.getBeanPropertyDefinition().orNull();
if (beanPropertyDefinition == null) {
return;
}
if (Annotations.findPropertyAnnotation(beanPropertyDefinition, NotNull.class).isPresent()) {
context.getBuilder().required(true);
} else if (Annotations.findPropertyAnnotation(beanPropertyDefinition, NotEmpty.class).isPresent()) {
context.getBuilder().required(true);
} else if (Annotations.findPropertyAnnotation(beanPropertyDefinition, NotBlank.class).isPresent()) {
context.getBuilder().required(true);
} else {
context.getBuilder().required(false);
}
}
@PostMapping("delBlogs")
public MyResponse delBlogByIds(@NotEmpty @RequestBody(required = false) int[] ids) {
if (blogService.delMultiBlogById(ids)) {
return MyResponse.createResponse(ResponseEnum.SUCC);
}
return MyResponse.createResponse(ResponseEnum.UNKNOWN_ERROR);
}
@POST
public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
@QueryParam("age") @PositiveOrZero int age) {
Person p = new Person(name, age);
personRepo.put(p.id, p);
return p.id;
}
@POST
public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
@QueryParam("age") @PositiveOrZero int age) {
Person p = new Person(name, age);
personRepo.put(p.id, p);
return p.id;
}
@POST
public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
@QueryParam("age") @PositiveOrZero int age) {
Person p = new Person(name, age);
peopleCollection.insertOne(p.toDocument());
return p.id;
}
public UserDto(Integer userId, @NotEmpty String username, String fullName, String description, String password) {
this.userId = userId;
this.username = username;
this.fullName = fullName;
this.description = description;
}