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, 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_ + \"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, > CACHES = CacheBuilder.newBuilder()
// 最大缓存 100 个
.maximumSize(1000)
// 设置写缓存后 5 秒钟过期
.expireAfterWrite(5, TimeUnit.SECONDS)
.build();
@Around(\"execution(public * *(..)) && @annotation(com.demo.testduplicate.Test1.LocalLock)\")
public 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, [] 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;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
继续阅读与本文标签相同的文章
上一篇 :
20种功能强大的跨平台渗透测试工具
下一篇 :
编程老司机带你玩转C语言指针
-
在 NAS SMB 卷上搭建 IIS + WordPress + MYSQL
2026-05-19栏目: 教程
-
SpringBoot2 整合 ElasticSearch框架,实现高性能搜索引擎
2026-05-19栏目: 教程
-
大神引路:新手云大使入门导引
2026-05-19栏目: 教程
-
一行命令导致的数据丢失,阿里工程师是如何恢复的?
2026-05-19栏目: 教程
-
二层、三层、四层交换机的区别!!
2026-05-19栏目: 教程
