美文网首页支付产品那些事itjava
防止表单重复提交(springboot,redis)

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

作者: LJasperliet | 来源:发表于2019-10-11 16:19 被阅读0次
   我们在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开源组件来实现原子操作。

相关文章

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

    通过在controller加上CheckSubmitForm注解 ,用户访问连接时,aop进行代理拦截 reque...

  • 防止表单重复提交

    嘿,大家好,今天我来介绍几种简单的防止表单重复提交的方法: 防止表单重复提交 方法一:前端方式 当点击提交或者保存...

  • 防止表单重复提交

    第一种(JavaScript): <%@ page language="java" import="java.ut...

  • 防止表单重复提交

    防止表单重复提交: 方法1:页面限制按钮 方法2:如图

  • 防止表单重复提交

    随机产生一个字符串(token) ,保存到session中,在向服务端发送请求时会携带token,本地token与...

  • 防止表单重复提交

    针对于重复提交的整体解决方案: 1.用redirect来解决重复提交的问题 2.点击一次之后,按钮失效 3.通过l...

  • 防止表单重复提交

    因为项目需要表单提交,可是发现了必须要防止用户提交,经过了几个小时的百度旅游总算找到的方法,其实说到底还是看官方手...

  • 防止表单重复提交

    一、前端控制(页面控制) 从前端控制主要方法就是点击提交后将提交按钮置灰,js中的提交方法不再响应提交事件 二、后...

  • 表单防止重复提交

    逻辑思路:1.提交数据之前判断当前提交按钮是否存在lock锁2.在ajax提交之前给提交按钮上锁3.ajax成功之...

  • 002_JavaWeb避免重复提交

    JavaWeb避免重复提交 现象 利用Session防止表单重复提交 问题: 测试代码 更多信息:www.itco...

网友评论

    本文标题:防止表单重复提交(springboot,redis)

    本文链接:https://www.haomeiwen.com/subject/pytxmctx.html