支付产品那些事itjava

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

2019-10-11  本文已影响0人  LJasperliet
   我们在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);
    }
@Data
public class SiteUserCommentDTO  extends RequesetDTO{

    private String itemCode ;

    private String formId;

    public String getFormId() {
        return itemCode ;
    }
}
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface CheckSubmitForm {
    int delaySeconds() default 5;
}
/**
 * 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开源组件来实现原子操作。

上一篇下一篇

猜你喜欢

热点阅读