当前位置:网站首页>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();
}
边栏推荐
- 2.15 summary
- Analysis report on the development prospect and investment strategy of the global and Chinese laser chip industry Ⓑ 2022 ~ 2027
- 当你真的学会DataBinding后,你会发现“这玩意真香”!
- 8 popular recommended style layout
- 刘对(火线安全)-多云环境的风险发现
- Anti fraud, refusing to gamble, safe payment | there are many online investment scams, so it's impossible to make money like this
- Use of shutter SQLite
- 介绍一种对 SAP GUI 里的收藏夹事务码管理工具增强的实现方案
- Social distance (cow infection)
- Cs5268 advantages replace ag9321mcq typec multi in one docking station scheme
猜你喜欢
玩转MongoDB—搭建MongoDB集群
学会使用LiveData和ViewModel,我相信会让你在写业务时变得轻松
MySQL 66 questions, 20000 words + 50 pictures in detail! Necessary for review
Explain IO multiplexing, select, poll, epoll in detail
When you really learn databinding, you will find "this thing is really fragrant"!
Cs5268 advantages replace ag9321mcq typec multi in one docking station scheme
Build a vc2010 development environment and create a tutorial of "realizing Tetris game in C language"
SAP 智能机器人流程自动化(iRPA)解决方案分享
【Flask】Flask启程与实现一个基于Flask的最小应用程序
French Data Protection Agency: using Google Analytics or violating gdpr
随机推荐
Camp division of common PLC programming software
Etcd 概要 机制 和使用场景
[anwangbei 2021] Rev WP
Chen Yu (Aqua) - Safety - & gt; Cloud Security - & gt; Multicloud security
[Jianzhi offer] 54 The k-th node of binary search tree
ArrayList capacity expansion mechanism and thread safety
Leetcode第一题:两数之和(3种语言)
洞态在某互联⽹⾦融科技企业的最佳落地实践
Understand the window query function of tdengine in one article
运行游戏时出现0xc000007b错误的解决方法[通俗易懂]
【241. 为运算表达式设计优先级】
Analysis report on the development trend and Prospect of new ceramic materials in the world and China Ⓐ 2022 ~ 2027
机器学习总结(一):线性回归、岭回归、Lasso回归
Report on the "14th five year plan" and scale prospect prediction of China's laser processing equipment manufacturing industry Ⓢ 2022 ~ 2028
Word2vec training Chinese word vector
China NdYAG crystal market research conclusion and development strategy proposal report Ⓥ 2022 ~ 2028
leetcode 322. Coin change (medium)
Enter the top six! Boyun's sales ranking in China's cloud management software market continues to rise
2. Sensor size "recommended collection"
2022年PMP项目管理考试敏捷知识点(6)