防止重复提交_后端实现

  前端页面,有一提交按钮,如何防止用户多次点击呢(比如支付页面的支付按钮,要做此限制,不然会扣多笔钱)?前端方面,可以给按钮加上单次点击后就出现loading效果(按钮不可点击 ,并会有一个转圈的动画);那后端呢,我们做一个双保险。大致思路是自定义注解,然后将注解加在请求的方法上;当然,注解还得搭配如下的aop或者拦截器。

自定义注解+aop

//定义一个注解:
package com.cvnavi.comm.annotation;

import java.lang.annotation.*;

/**
 * @description: 防止重复提交
 * @author: gs
 * @version:
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RepeatSubmit {

    /**
     * 重复提交时间限制,默认3秒
     * @return
     */
    int limit() default 3;

}


//编写切面类(结合redis):
package com.cvnavi.component.security.aspect;

import com.cvnavi.comm.annotation.RepeatSubmit;
import com.cvnavi.component.security.util.AuthUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.auth.AUTH;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

@Component
@Aspect
@Slf4j
public class RepeatSubmitAspect {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Pointcut("@annotation(com.cvnavi.comm.annotation.RepeatSubmit)")
    public void repeatCheck() {}

    @Around(value = "repeatCheck()")
    public void check(ProceedingJoinPoint point) throws Throwable {
        long start = System.currentTimeMillis();
        String key = "";
        try {
            //获取访问的方法
            Method method = ((MethodSignature)point.getSignature()).getMethod();
            String className = method.getDeclaringClass().getName();
            //模拟获取登录用户Id
            Long id = AuthUtil.getUser().getId();
            //类的全路径_方法名_userId
            key = className + "_" + method.getName() + "_" + id;
            //获取过期时间
            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
            //没有值返回true,有值返回false
            Boolean absent = redisTemplate.opsForValue().setIfAbsent(key, "exist", annotation.limit(), TimeUnit.SECONDS);
            Assert.isTrue(absent, "请勿重复提交");
            point.proceed();
        }
        catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
        finally {
            //redisTemplate.delete(key);
        }
    }

}

 

自定义注解+拦截器

  注解同上,不做赘述;

//拦截器如下:
package com.cvnavi.component.security.component;

import com.cvnavi.comm.annotation.RepeatSubmit;
import com.cvnavi.comm.dto.ResponseResult;
import com.cvnavi.component.data.cache.RedisCache;
import com.cvnavi.component.security.util.AuthUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.ObjectWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 防止重复提交拦截器
 *
 * @author gs
 */
@Component
public class RepeatSubmitInterceptor extends HandlerInterceptorAdapter {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    private static final ObjectMapper objectMapper = new ObjectMapper();

    private static final ObjectWriter objectWriter = objectMapper.writerWithDefaultPrettyPrinter();


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RepeatSubmit annotation = method.getAnnotation(RepeatSubmit.class);
            if (annotation != null) {
                Long id = AuthUtil.getUser().getId();
                String key = request.getRequestURI() + "_" + id;
                Boolean absent = redisTemplate.opsForValue().setIfAbsent(key, "exist", annotation.limit(), TimeUnit.SECONDS);
                if(absent) {
                    return true;
                }
                else{
                    ResponseResult<Object> result = ResponseResult.failed("不允许重复提交");
                    response.setContentType("application/json");
                    response.setCharacterEncoding("utf-8");
                    response.getWriter().print(objectWriter.writeValueAsString(result));
                    return false;
                }
            }
            return true;
        }
        else {
            return super.preHandle(request, response, handler);
        }
    }


}


//注册拦截器:
package com.cvnavi.component.security.config;

import com.cvnavi.component.security.component.RepeatSubmitInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Autowired
    private RepeatSubmitInterceptor repeatSubmitInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry){
        registry.addInterceptor(repeatSubmitInterceptor).addPathPatterns("/**");
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值