在表單顯示頁面
1
//生成一個formhash,算法可以自己定,不隨便重復就可以了
2
String formhash = MD5.encode(Long.toString(new Date().getTime()));
3
//讀取當前session里面的hashCode集合,此處使用了Set,方便判斷。
4
Set<String> formhashSession = (Set<String>) session.getAttribute("formhashSession");
5
if (formhashSession == null) {
6
formhashSession = new HashSet<String>();
7
}
8
// 檢測重復問題
9
while (formhashSession.contains(formhash)) {
10
formhash = MD5.encode(Long.toString(new Date().getTime()));
11
}
12
// 保存到session里面
13
formhashSession.add(formhash);
14
// 保存
15
session.setAttribute("formhashSession", formhashSession);
表單里面增加如下字段
2

3

4

5

6

7

8

9

10

11

12

13

14

15

<input type="hidden" name="formhash" id="formhash" value="<%=formhash%>" />
在表單提交頁面進行如下處理
1
// 拿到表單的formhash
2
String formhash = upload.getParameter("formhash");
3
// 拿到session里面的集合
4
Set<String> formhashSession = (Set<String>) session.getAttribute("formhashSession");
5
// 如果沒有,則是重復提交,或者非法提交
6
if (formhashSession == null || !formhashSession.contains(formhash)) {
7
out.println("請不要重復提交!");
8
return;
9
}
10
// 下面進行其它的操作
11
//
12
// 最后,如果操作成功,從session里面把這個formhash 刪掉!
13
// 以免用戶少填寫了某個字段,造成表單無法再次提交
14
formhashSession.remove(formhash);
15
session.setAttribute("formhashSession", formhashSession);

2

3

4

5

6

7

8

9

10

11

12

13

14

15
