Principle: The session in the new page to save token random code, when the save validation, after the deletion, when the click on the save again due to the server side of the session no longer exists, all can not be verified through.
注解Token代码:
@Target
(ElementType.METHOD)
@Retention
(RetentionPolicy.RUNTIME)
public
@interface
Token {
boolean
save()
default
false
;
boolean
remove()
default
false
;
}
Interceptor Tokeninterceptor Code:
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
;
}
}
Then add the following in the spring MVC configuration file:
<!-- 拦截器配置 -->
<
mvc:interceptors
>
<!-- 配置Shiro拦截器,实现注册用户的注入 -->
<
mvc:interceptor
>
<
mvc:mapping
path
=
"/**"
/>
<
bean
class
=
"com.storezhang.video.shiro.ShiroInterceptor"
/>
</
mvc:interceptor
>
<!-- 配置Token拦截器,防止用户重复提交数据 -->
<
mvc:interceptor
>
<
mvc:mapping
path
=
"/**"
/>
<
bean
class
=
"com.storezhang.web.spring.TokenInterceptor"
/>
</
mvc:interceptor
>
</
mvc:interceptors
>
The relevant code has been commented, I believe you can read.
The use of this method is to increase @token (save=true) on the controller that needs to generate tokens, and add @token (remove=true) on the controller that needs to check for duplicate submissions.
In addition, you need to add the following code to the form in the view:
< input type = "hidden" name = "token" value = "${token}" /> |
It's done, so try to see if your data can be submitted again.
Spring MVC Interceptor + annotation method to prevent form repeating submission