Srping註解方式防止重複提交原理

Srping註解方式防止重複提交原理

方法一: Springmvc使用Token

使用token的邏輯是,給所有的url加一個攔截器,在攔截器裏面用java的UUID生成一個隨機的UUID並把這個UUID放到session裏面,然後在瀏覽器做數據提交的時候將此UUID提交到服務器。服務器在接收到此UUID後,檢查一下該UUID是否已經被提交,如果已經被提交,則不讓邏輯繼續執行下去…**

1 首先要定義一個annotation: 用@Retention 和 @Target 標註接口

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Token {
    boolean save() default false;
    boolean remove() default false;
}

2 定義攔截器TokenInterceptor:

public class TokenInterceptor extends HandlerInterceptorAdapter {

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (handler instanceof HandlerMethod) {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Token annotation = method.getAnnotation(Token.class);
        if (annotation != null) {
            boolean needSaveSession = annotation.save();
            if (needSaveSession) {
                request.getSession(false).setAttribute("token", UUID.randomUUID().toString());
            }
            boolean needRemoveSession = annotation.remove();
            if (needRemoveSession) {
                if (isRepeatSubmit(request)) {
                    return false;
                }
                request.getSession(false).removeAttribute("token");
            }
        }
        return true;
    } else {
        return super.preHandle(request, response, handler);
    }
}

private boolean isRepeatSubmit(HttpServletRequest request) {
    String serverToken = (String) request.getSession(false).getAttribute("token");
    if (serverToken == null) {
        return true;
    }
    String clinetToken = request.getParameter("token");
    if (clinetToken == null) {
        return true;
    }
    if (!serverToken.equals(clinetToken)) {
        return true;
    }
    return false;
}
}

Spring MVC的配置文件里加入:

   <mvc:interceptors>  
 <!-- 使用bean定義一個Interceptor,直接定義在mvc:interceptors根下面的Interceptor將攔截所有的請求 --> 
        <mvc:interceptor>  
            <mvc:mapping path="/**"/>  
            <!-- 定義在mvc:interceptor下面的表示是對特定的請求才進行攔截的 -->  
            <bean class="****包名****.TokenInterceptor"/>  
        </mvc:interceptor>  
    </mvc:interceptors>



@RequestMapping("/add.jspf")
@Token(save=true)
public String add() {
    //省略
    return TPL_BASE + "index";
}
 
@RequestMapping("/save.jspf")
@Token(remove=true)
public void save() {
	//省略
}

用法:

在Controller類的用於定向到添加/修改操作的方法上增加自定義的註解類 @Token(save=true)

在Controller類的用於表單提交保存的的方法上增加@Token(remove=true)

在表單中增加 用於存儲token,每次需要報token值傳入到後臺類,用於從緩存對比是否是重複提交操作

方法二:springboot中用註解方式

每次操作,生成的key存放於緩存中,比如用google的Gruava或者Redis做緩存

定義Annotation類

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface LocalLock {

    /**
     * @author fly
     */
    String key() default "";

    /**
     * 過期時間 TODO 由於用的 guava 暫時就忽略這屬性吧 集成 redis 需要用到
     *
     * @author fly
     */
    int expire() default 5;
}

設置攔截類

@Aspect
@Configuration
public class LockMethodInterceptor {

    private static final Cache<String, Object> CACHES = CacheBuilder.newBuilder()
            // 最大緩存 100 個
            .maximumSize(1000)
            // 設置寫緩存後 5 秒鐘過期
            .expireAfterWrite(5, TimeUnit.SECONDS)
            .build();

    @Around("execution(public * *(..)) && @annotation(com.demo.testduplicate.Test1.LocalLock)")
    public Object interceptor(ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        LocalLock localLock = method.getAnnotation(LocalLock.class);
        String key = getKey(localLock.key(), pjp.getArgs());
        if (!StringUtils.isEmpty(key)) {
            if (CACHES.getIfPresent(key) != null) {
                throw new RuntimeException("請勿重複請求");
            }
            // 如果是第一次請求,就將 key 當前對象壓入緩存中
            CACHES.put(key, key);
        }
        try {
            return pjp.proceed();
        } catch (Throwable throwable) {
            throw new RuntimeException("服務器異常");
        } finally {
            // TODO 爲了演示效果,這裏就不調用 CACHES.invalidate(key); 代碼了
        }
    }

    /**
     * key 的生成策略,如果想靈活可以寫成接口與實現類的方式(TODO 後續講解)
     *
     * @param keyExpress 表達式
     * @param args       參數
     * @return 生成的key
     */
    private String getKey(String keyExpress, Object[] args) {
        for (int i = 0; i < args.length; i++) {
            keyExpress = keyExpress.replace("arg[" + i + "]", args[i].toString());
        }
        return keyExpress;
    }
}

Controller類引用

@RestController
@RequestMapping("/books")
public class BookController {

    @LocalLock(key = "book:arg[0]")
    @GetMapping
    public String save(@RequestParam String token) {
        return "success - " + token;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章