@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
|
|
相关代码已经注释,相信你能看懂。
关于这个方法的用法是:在需要生成token的controller上增加@Token(save=true),而在需要检查重复提交的controller上添加@Token(remove=true)就可以了。
另外,你需要在view里在form里增加下面代码: