Spring注解方式防止重復(fù)提交原理詳解
Srping注解方式防止重復(fù)提交原理分析,供大家參考,具體內(nèi)容如下
方法一: Springmvc使用Token
使用token的邏輯是,給所有的url加一個攔截器,在攔截器里面用java的UUID生成一個隨機(jī)的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下面的表示是對特定的請求才進(jìn)行攔截的 -->
<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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Mybatis攔截器實現(xiàn)數(shù)據(jù)權(quán)限的示例代碼
在我們?nèi)粘i_發(fā)過程中,通常會涉及到數(shù)據(jù)權(quán)限問題,本文主要介紹了Mybatis攔截器實現(xiàn)數(shù)據(jù)權(quán)限的示例代碼,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2022-03-03
mybatis-plus開啟sql打印的三種方式總結(jié)
這篇文章主要給大家介紹了mybatisplus開啟sql打印的三種方式,文章通過代碼示例介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作有一定的參考價值,需要的朋友可以參考下2023-11-11
基于controller使用map接收參數(shù)的注意事項
這篇文章主要介紹了基于controller使用map接收參數(shù)的注意事項,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10
Java實現(xiàn)自定義ArrayList類的示例代碼
這篇文章主要為大家簡單的介紹ArrayList一下里面的add方法、size方法、isEmpty方法,以及如何實現(xiàn)自定義ArrayList類,感興趣的可以了解一下2022-08-08

