当前位置: 移动技术网 > IT编程>开发语言>Java > Spring注解方式防止重复提交原理详解

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

2019年07月19日  | 移动技术网IT编程  | 我要评论
srping注解方式防止重复提交原理分析,供大家参考,具体内容如下 方法一: springmvc使用token 使用token的逻辑是,给所有的url加一个拦截器,在拦

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;
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网