前后台分离时,springboot框架防止前台重复提交

1,在pom.xml文件中引入缓存的jar包


    com.google.guava
    guava
    21.0

2,自定义一个注解类,将来用在禁止重复提交的方法上

public @interface FormCommit {

    String name() default "name:";
}

3,自定义一个切面类,利用aspect实现切入所有方法

@Aspect
@Configuration
public class SubmitAspect {

    private static final Cache CACHES = CacheBuilder.newBuilder()
            // 最大缓存 100 个
            .maximumSize(100)
            // 设置缓存过期时间为S
            .expireAfterWrite(3, TimeUnit.SECONDS)
            .build();

    @Around("execution(public * *(..)) && @annotation(com.ding.web.FormCommit)")
    public Object interceptor(ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        FormCommit form= method.getAnnotation(FormCommit.class);
        String key = getCacheKey(method, pjp.getArgs());
        if (!StringUtils.isEmpty(key)) {
            if (CACHES.getIfPresent(key) != null) {
                ResultResponse resultResponse = new ResultResponse();
                resultResponse.setData(null);
                resultResponse.setMsg("请勿重复请求");
                resultResponse.setCode(405);
                return  resultResponse;

            }
            // 如果是第一次请求,就将key存入缓存中
            CACHES.put(key, key);
        }
        try {
            return pjp.proceed();
        } catch (Throwable throwable) {
            throw new RuntimeException("服务器异常");
        } finally {
            CACHES.invalidate(key);
        }
    }

    /**
     *将来还要加上用户的唯一标识
     */
    private String getCacheKey(Method method Object[] args) {
        return method.getName() + args[0];
    }


}

4,在禁止提交的方法上加上注解@FormCommit

前后台分离时,springboot框架防止前台重复提交_第1张图片

 

 

你可能感兴趣的:(java)