防重复提交常见解决方案:http://patrick002.iteye.com/blog/2197521
定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface FormRepeatSubmitValidation {
String value() default "表单重复提交验证";
}
定义切面
@Aspect
@Component
public class FormRepeatSubmitAspect {
/**
* 日志记录
*/
private static final Logger logger = LoggerFactory.getLogger(FormRepeatSubmitAspect.class);
@Autowired
private RedisTemplate<String, Object> redisTemplate;
/**
* 定义切入点
*/
@Pointcut("@annotation(com.geekymv.FormRepeatSubmitValidation)")
public void doAspect() {
}
@Before("doAspect()")
public void doBefore(JoinPoint pjp) {
Object[] args = pjp.getArgs();
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
Object target = pjp.getTarget();
String params = JSON.toJSONString(args);
if(logger.isDebugEnabled()) {
logger.debug("before methodName: {}", method.getName());
logger.debug("before args: {}", params);
logger.debug("before target: {}", target);
}
boolean flag = method.isAnnotationPresent(FormRepeatSubmitValidation.class) ;
if(flag) {
FormRepeatSubmitValidation formRepeatSubmitValidation = method.getAnnotation(FormRepeatSubmitValidation.class);
logger.info("FormRepeatSubmitValidation-->{}", formRepeatSubmitValidation.value());
// 将入参作为key自增值存入redis
ValueOperations<String, Object> value = redisTemplate.opsForValue();
Long result = value.increment(params, 1);
// 判断返回值是否大于1,如果是则重复提交
if(result > 1) {
throw new BaseException(ErrorMessage.FORM_REPEAT_SUBMIT);
}
redisTemplate.expire(params, 5, TimeUnit.SECONDS); // 设置过期时间5秒
}
}
@After("doAspect()")
public void doAfter(JoinPoint pjp) {
Object[] args = pjp.getArgs();
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod();
Object target = pjp.getTarget();
String params = JSON.toJSONString(args);
if(logger.isDebugEnabled()) {
logger.debug("after methodName: {}", method.getName());
logger.debug("after args: {}", params);
logger.debug("after target: {}", target);
}
boolean flag = method.isAnnotationPresent(FormRepeatSubmitValidation.class) ;
if(flag) {
// 清除redis中key为入参的数据,对于引用类型的变量有可能在业务代码中被修改
redisTemplate.delete(params);
}
}
}
添加配置spring-aop.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 启动@AspectJ支持 -->
<aop:aspectj-autoproxy expose-proxy="true" proxy-target-class="true" />
</beans>
「更多精彩内容请关注公众号geekymv,喜欢请分享给更多的朋友哦」