当前位置:网站首页>User defined annotation realizes the function of verifying information
User defined annotation realizes the function of verifying information
2022-07-01 13:45:00 【Engineering students who like history】
Custom annotations implement validation logic
- Guide pack
<!-- hibernate Validation framework -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
- Definition BO object , Business object from the front end , The properties in the object need to be verified
package com.imooc.boapi;
//import com.imooc.annotationcustom.VlogId;
import com.imooc.annotationcustom.VlogId;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class VlogBOApi {
private String id;
@VlogId(message = " The user doesn't exist , Do not insert video ")
private String vlogerId;
private String url;
private String cover;
private String title;
private Integer width;
private Integer height;
private Integer likeCounts;
private Integer commentsCounts;
}
- Define a verification annotation
package com.imooc.annotationcustom;
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({
ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = VlogIdValidator.class) // Logical processing class of verification
public @interface VlogId {
String message();
/** * take validator To classify , Different classes group Will perform different validator operation * * @return validator The classification type of */
Class<?>[] groups() default {
};
/** * Mainly aimed at bean, Rarely used * * @return load */
Class<? extends Payload>[] payload() default {
};
}
- At the same time, a verification class is required , Implement a logic of annotation verification
package com.imooc.annotationcustom;
import com.imooc.mapper.UsersMapper;
import com.imooc.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
@Slf4j
@Component
public class VlogIdValidator implements ConstraintValidator<VlogId, String> {
@Autowired
UsersMapper usersMapper;
@Override
public void initialize(VlogId constraintAnnotation) {
log.info(" Annotation logic initialization ");
}
@Override
public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
Users user = new Users();
user.setId(s);
Users reslut = usersMapper.selectByPrimaryKey(user);
System.out.println(" Annotation blocking takes effect +package com.imooc.annotationcustom;");
if (reslut == null) {
return false;
} else {
return true;
}
}
}
- Business code
@PostMapping("publish")
public GraceJSONResult publish(@Valid @RequestBody VlogBOApi vlogBO) {
// vlogService.createVlog(vlogBO);
return GraceJSONResult.ok();
}
- Verification failed, exception , Define a global exception capture , Return this error to the front end
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public GraceJSONResult returnMethodArgumentNotValid(MethodArgumentNotValidException e) {
BindingResult result = e.getBindingResult();
Map<String, String> map = getErrors(result);
return GraceJSONResult.errorMap(map);
}
Customize annotations to simplify development
Purpose : Do a function to intercept likes . The process : You need to determine how many times you like after blocking
- Definition notes :
package com.imooc.annotationcustom;
import java.lang.annotation.*;
@Inherited
@Documented
@Target({
ElementType.FIELD, ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestLimit {
/** * Within time Seconds per unit * @return */
int second() default 10;
/*** * Number of visits allowed * @return */
int maxCount() default 5;
}
- Interceptor code , Here you need to get the custom annotation on the interface handlerMethod.getMethodAnnotation
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
// obtain RequestLimit annotation
RequestLimit requestLimit = handlerMethod.getMethodAnnotation(RequestLimit.class);
if (null == requestLimit) {
System.out.println(" No comments were obtained ");
return true; // There is no limit for each annotation , Many times ok
}
// Limited time frame
int seconds = requestLimit.second();
// Limit the maximum number of times in the time
int maxCount = requestLimit.maxCount();
// Get users ip
String userIp = IPUtil.getRequestIp(request);
// Judge redis If there ip
boolean keyIsExist = redis.keyIsExist(LIKE_VLOG_OPERATE_COUNT + ":" + userIp);
// Without this key , Indicates that the current user is 20s I didn't like it in , Because this interceptor is the backend interface that intercepts likes , So if you don't have this key, set a key
if (keyIsExist == false) {
redis.set(LIKE_VLOG_OPERATE_COUNT + ":" + userIp, "0", seconds);
System.out.println("ok");
return true;
}
// return true, It is necessary to determine the number of values corresponding to this key
String res = redis.get(LIKE_VLOG_OPERATE_COUNT + ":" + userIp);
if (Integer.valueOf(res) >= maxCount) {
GraceException.display(ResponseStatusEnum.LIKE_VLOG_WAIT_ERROR);
return false;
}
}
return true;
}
- Business code
@PostMapping("like")
//TODO: Debugging is needed here
@RequestLimit(maxCount = 3, second = 60)
public GraceJSONResult like(@RequestParam String userId,
@RequestParam String vlogerId,
@RequestParam String vlogId,
HttpServletRequest request) {
vlogService.userLikeVlog(userId, vlogId);
redis.increment(REDIS_VLOGER_BE_LIKED_COUNTS + ":" + vlogerId, 1);
redis.increment(REDIS_VLOG_BE_LIKED_COUNTS + ":" + vlogId, 1);
redis.set(REDIS_USER_LIKE_VLOG + ":" + userId + ":" + vlogId, "1");
//------------------------------------------//
// New function , Limit the number of likes ,
String userIp = IPUtil.getRequestIp(request);
redis.increment(LIKE_VLOG_OPERATE_COUNT + ":" + userIp,1);
//-------------------------------------------//
return GraceJSONResult.ok();
}
边栏推荐
- [anwangbei 2021] Rev WP
- 2022上半年英特尔有哪些“硬核创新”?看这张图就知道了!
- Research Report on China's software outsourcing industry investment strategy and the 14th five year plan Ⓡ 2022 ~ 2028
- 焱融看 | 混合云时代下,如何制定多云策略
- The best landing practice of cave state in an Internet ⽹⾦ financial technology enterprise
- leetcode 322. Coin change (medium)
- SAP intelligent robot process automation (IRPA) solution sharing
- 04 redis source code data structure dictionary
- Cs5268 advantages replace ag9321mcq typec multi in one docking station scheme
- spark源码阅读总纲
猜你喜欢

玩转gRPC—不同编程语言间通信

Chen Yu (Aqua) - Safety - & gt; Cloud Security - & gt; Multicloud security

8 popular recommended style layout

当你真的学会DataBinding后,你会发现“这玩意真香”!

【NLP】预训练模型——GPT1

Station B was scolded on the hot search..

开源者的自我修养|为 ShardingSphere 贡献了千万行代码的程序员,后来当了 CEO

Error:Kotlin: Module was compiled with an incompatible version of Kotlin. The binary version of its

Fiori applications are shared through the enhancement of adaptation project

面试题目总结(1) https中间人攻击,ConcurrentHashMap的原理 ,serialVersionUID常量,redis单线程,
随机推荐
[machine learning] VAE variational self encoder learning notes
La taille de la pile spécifiée est petite, spécifiée à la sortie 328k
Learning to use livedata and ViewModel will make it easier for you to write business
Enter the top six! Boyun's sales ranking in China's cloud management software market continues to rise
MySQL 66 questions, 20000 words + 50 pictures in detail! Necessary for review
Global and Chinese n-butanol acetic acid market development trend and prospect forecast report Ⓧ 2022 ~ 2028
A Fletter version of Notepad
孔松(信通院)-数字化时代云安全能力建设及趋势
7. Icons
Apache-atlas-2.2.0 independent compilation and deployment
Beidou communication module Beidou GPS module Beidou communication terminal DTU
Kongsong (Xintong Institute) - cloud security capacity building and trend in the digital era
详细讲解面试的 IO多路复用,select,poll,epoll
机器学习总结(一):线性回归、岭回归、Lasso回归
leetcode 322. Coin Change 零钱兑换(中等)
【NLP】预训练模型——GPT1
受益互联网出海 汇量科技业绩重回高增长
Global and Chinese silicone defoamer production and marketing demand and investment forecast analysis report Ⓨ 2022 ~ 2027
Benefiting from the Internet, the scientific and technological performance of overseas exchange volume has returned to high growth
2022 · 让我带你Jetpack架构组件从入门到精通 — Lifecycle