溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Spring注解方式防止重復(fù)提交原理詳解

發(fā)布時間:2020-10-03 18:17:04 來源:腳本之家 閱讀:232 作者:xdy3008 欄目:編程語言

Srping注解方式防止重復(fù)提交原理分析,供大家參考,具體內(nèi)容如下

方法一: Springmvc使用Token

使用token的邏輯是,給所有的url加一個攔截器,在攔截器里面用java的UUID生成一個隨機的UUID并把這個UUID放到session里面,然后在瀏覽器做數(shù)據(jù)提交的時候?qū)⒋薝UID提交到服務(wù)器。服務(wù)器在接收到此UUID后,檢查一下該UUID是否已經(jīng)被提交,如果已經(jīng)被提交,則不讓邏輯繼續(xù)執(zhí)行下去…**

1 首先要定義一個annotation: 用@Retention 和 @Target 標(biāo)注接口

@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值傳入到后臺類,用于從緩存對比是否是重復(fù)提交操作

方法二: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;
}

設(shè)置攔截類

@Aspect
@Configuration
public class LockMethodInterceptor {

  private static final Cache<String, Object> CACHES = CacheBuilder.newBuilder()
      // 最大緩存 100 個
      .maximumSize(1000)
      // 設(shè)置寫緩存后 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("請勿重復(fù)請求");
      }
      // 如果是第一次請求,就將 key 當(dāng)前對象壓入緩存中
      CACHES.put(key, key);
    }
    try {
      return pjp.proceed();
    } catch (Throwable throwable) {
      throw new RuntimeException("服務(wù)器異常");
    } finally {
      // TODO 為了演示效果,這里就不調(diào)用 CACHES.invalidate(key); 代碼了
    }
  }

  /**
   * key 的生成策略,如果想靈活可以寫成接口與實現(xiàn)類的方式(TODO 后續(xù)講解)
   *
   * @param keyExpress 表達(dá)式
   * @param args    參數(shù)
   * @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;
 }
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI