通過Redis和AOP實現防重提交

下面的代碼是使用shiro做安全控制的後臺管理系統的防重提交。
可根據實際情況進行修改

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
 * @類名稱 ResubmitAop
 * @類描述 定義切面,進行重複提交攔截
 */
@Aspect
@Component
public class ResubmitAop {

    private static final Logger logger = LoggerFactory.getLogger(ResubmitAop.class);

    @Around("execution(* com.controller..*(..)) && @annotation(resubmit)")
    public Object doInterceptor(ProceedingJoinPoint pjp, Resubmit resubmit) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals = subject.getPrincipals();
        String token = principals.toString();// 訪問令牌
        String path = request.getServletPath();// 訪問路徑
        String key = PREFIX + path + ":" + token;
        if (CacheUtils.exists(key)) {// 如果緩存中有這個url視爲重複提交
            logger.info("重複提交攔截,account:{},path:{}", JwtUtil.getAccount(token), path);
            throw new Exception("");
        }
        CacheUtils.set(key, value, EXPIRE_TIME);
        return pjp.proceed();
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章