服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|JavaScript|易语言|

服务器之家 - 编程语言 - Java教程 - Spring注解方式防止重复提交原理详解

Spring注解方式防止重复提交原理详解

2021-06-17 11:31xdy3008 Java教程

这篇文章主要为大家详细介绍了Spring注解方式防止重复提交原理,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

srping注解方式防止重复提交原理分析,供大家参考,具体内容如下

方法一: springmvc使用token

使用token的逻辑是,给所有的url加一个拦截器,在拦截器里面用java的uuid生成一个随机的uuid并把这个uuid放到session里面,然后在浏览器做数据提交的时候将此uuid提交到服务器。服务器在接收到此uuid后,检查一下该uuid是否已经被提交,如果已经被提交,则不让逻辑继续执行下去…**

1 首先要定义一个annotation: 用@retention 和 @target 标注接口

?
1
2
3
4
5
6
@target(elementtype.method)
@retention(retentionpolicy.runtime)
public @interface token {
  boolean save() default false;
  boolean remove() default false;
}

2 定义拦截器tokeninterceptor:

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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的配置文件里加入:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<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类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@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;
}

设置拦截类

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@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类引用

?
1
2
3
4
5
6
7
8
9
10
@restcontroller
@requestmapping("/books")
public class bookcontroller {
 
 @locallock(key = "book:arg[0]")
 @getmapping
 public string save(@requestparam string token) {
  return "success - " + token;
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/xdy3008/article/details/84452587

延伸 · 阅读

精彩推荐