您现在的位置是:首页 > 文章详情

防止表单重复提交(springboot,redis)

日期:2019-12-24点击:620

我们在web项目中经常需要在后台对用户提交的表单进行校验防止重复提交。下面通过springboot的aop、redis来解决表单重复提交的问题。


通过在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,也可以是我们自己业务定义的一个关键字。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业务范围尽量要小,太大可能对用户的其他表单提交有影响。

@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("重复表单提交检验 失效: 参数错误:fromId-{},uicId-{}",formId,userId);
}

}

return joinPoint.proceed();
}
}


注意:代码中stringRedisTemplate的setNx 和 expire 不是原子操作。可以使用lua脚本实现或者Jedis开源组件来实现原子操作。


原文链接:https://blog.roncoo.com/article/1209392266438352897
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章