struts令牌机制防止重复提交 savetoken(request) resetToken(request)

来源:岁月联盟 编辑:exp 时间:2012-09-07

在web开发中,常会遇到这样的问题:点击了页面的提交按钮了之后,数据保存进数据库,之后按F5刷新页面,又产生了一条同样的数据。解决方法:struts令牌机制。

struts令牌的原理很简单:在进入页面之前struts产生一个唯一的值,并且将其保存在session context中,之后跳转页面的时候,将这个值设置为JSP页面的一个隐藏的值(<inputtype="hidden"id="org.apache.struts.taglib.html.TOKEN"name="org.apache.struts.taglib.html.TOKEN"value="XXXXXXXXXX">)。当用户提交的时候,在后台会将页面这个隐藏域中的值同之前保存在session中的值进行比较。在后台同时需要调用resetToken(request);如果一致则提交成功,否则失败。第一次提交,页面和session的值一致,提交成功。第二次,由于调用resetToken(request);方法,已经将session中的值清除了,必然和页面的值不一致,提交失败。

基本的步骤:

The flow is usually like this:

On initial request:
1. saveToken(request)
2. forward to JSP

When user submits form:
3. check if isTokenValid(request)
4. if true, process request then call resetToken(); otherwise, submission is not valid.

What's happening under the hood:
@1 Struts will generate a unique value (the token) and keep it in the session context
@2 When the JSP is rendered, Struts inserts the token as a hidden field
@3 The hidden field token is submitted along with the rest of the form and isValidToken() checks the value that came in with the current request against the value that was saved in the session context by the most recent saveToken() call. If the two token values match, the submission is valid.

初始化request的时候

1、调用saveToken(request)方法

2、跳转JSP页面

用户提交表单的时候

3、检查页面的值和session中保存的是否一致

4、如果一致,则处理请求,之后调用resetToken();方法,如果不一致提交失败(不处理该次请求)

在这下面都进行了哪些操作:

@1struts产生唯一值,保存在session context中

@2当JSP页面进行渲染时,struts插入token值作为一个隐藏域

@3隐藏域,随用户提交表单一起提交。后台isValidToken()方法检查当前请求的隐藏域的值和后台session是否一致,一致提交成功,否则失败。