我們在web項目中經(jīng)常需要在后臺對用戶提交的表單進行校驗防止重復(fù)提交。下面通過springboot的aop逼肯、redis來解決表單重復(fù)提交的問題。
通過在controller加上CheckSubmitForm注解 桃煎,用戶訪問連接時篮幢,aop進行代理攔截
@PostMapping("/comment/add")
@CheckSubmitForm(delaySeconds = 6)
public MallTradeResult comment(@RequestBody SiteUserCommentDTO siteUserCommentDTO,@User UserDTO userDTO) {
siteUserCommentDTO.setUserId(userDTO.getUicId());
siteUserCommentDTO.setPhone(userDTO.getPhoneNumber());
siteUserCommentDTO.setNickName(userDTO.getUserName());
siteUserCommentDTO.setUserHeadImg(userDTO.getAvatarUrl());
return siteCommentFacade.add(siteUserCommentDTO);
}
- requesetDTO中加入formId字段,fromId可以是前端提交的fromId为迈,也可以是我們自己業(yè)務(wù)定義的一個關(guān)鍵字洲拇。fromId用做redis 的key
@Data
public class SiteUserCommentDTO extends RequesetDTO{
private String itemCode ;
private String formId;
public String getFormId() {
return itemCode ;
}
}
- CheckSubmitFrom 注解是攔截哪些請求對用戶提交的表單進行校驗
作者項目中是使用 methodname:userId:formId來作為redis key奈揍。例如下圖實例key為comment:userId:itemCode 表示用戶userId對某件商品itemCode的評價comment。如果key存在則阻止提交赋续。也可以由前端傳遞formId直接作為key男翰。key業(yè)務(wù)范圍盡量要小,太大可能對用戶的其他表單提交有影響纽乱。
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CheckSubmitForm {
int delaySeconds() default 5;
}
- ReSubmitAspect 定義aop切面
/**
* Description:
*
* @author lixj on 2019/10/11.
*/
@Slf4j
@Component
@Aspect
public class ReSubmitAspect {
@Autowired
private StringRedisTemplate stringRedisTemplate;
private String keyId = "formId";
@Around("@annotation(com.fcbox.mall.web.support.CheckSubmitForm)")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable{
log.info("resubmitApsec do around");
MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
CheckSubmitForm checkSubmitForm = methodSignature.getMethod().getAnnotation(CheckSubmitForm.class);
if (checkSubmitForm == null) {
return joinPoint.proceed();
} else {
Object[] args = joinPoint.getArgs();
String formId = null;
String userId = null;
for (Object arg : args) {
if (StringUtils.isEmpty(formId)) {
JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(arg));
if (!StringUtils.isEmpty(jsonObject.getString(keyId))) {
formId = jsonObject.getString(keyId);
}
}
if (StringUtils.isEmpty(userId)) {
if (arg.getClass().getAnnotation(User.class) != null) {
UserDTO userDTO = (UserDTO)arg;
userId = userDTO.getUicId().toString();
}
}
}
if (!StringUtils.isEmpty(formId) && !StringUtils.isEmpty(userId)) {
Class<?> returnType = ((MethodSignature) joinPoint.getSignature()).getMethod().getReturnType();
String redisKey = ((MethodSignature) joinPoint.getSignature()).getMethod().getName().concat(":").concat(userId)
.concat(":").concat(formId);
log.info("resubmit {}", redisKey, checkSubmitForm.delaySeconds());
boolean submitAble = stringRedisTemplate.opsForValue().setIfAbsent(redisKey, "1");
if (!submitAble) {
long ttl = stringRedisTemplate.getExpire(redisKey);
if (ttl > 0) {
return MallTradeResult.fail(ResultCode.REPEAT_SUBMIT_ERROR.getCode(), ResultCode.REPEAT_SUBMIT_ERROR.getMsg());
}
}
}
stringRedisTemplate.expire(redisKey, checkSubmitForm.delaySeconds(), TimeUnit.SECONDS);
return joinPoint.proceed();
} else {
log.error("重復(fù)表單提交檢驗 失效: 參數(shù)錯誤:fromId-{},uicId-{}",formId,userId);
}
}
return joinPoint.proceed();
}
}
** 注意:代碼中stringRedisTemplate的setNx 和 expire 不是原子操作蛾绎。可以使用lua腳本實現(xiàn)或者Jedis開源組件來實現(xiàn)原子操作鸦列。