程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> JSP編程 >> 關於JSP >> struts令牌機制防止重復提交 savetoken(request) resetToken(request)

struts令牌機制防止重復提交 savetoken(request) resetToken(request)

編輯:關於JSP

在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是否一致,一致提交成功,否則失敗。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved