服務器端在處理到達的請求之前,會將請求中包含的令牌值與保存在當前用戶會話中的令牌值進行比較,看是否匹配。在處理完該請求後,且在答覆發送給客戶端之前,將會產生一個新的令牌,該令牌除傳給客戶端以外,也會將用戶會話中保存的舊的令牌進行替換。這樣如果用戶回退到剛纔的提交頁面並再次提交的話,客戶端傳過來的令牌就和服務器端的令牌不一致,從而有效地防止了重複提交的發生。
根據用戶會話ID和當前系統時間來生成一個唯一(對於每個會話)令牌的,具體實現可以參考SynchroToken類中的generateToken()方法。
1、在待提交的jsp頁面中生成令牌並保存在session和request(在form表單裏增加一個hiddean元素);
//設置同步令牌值,同時存放在session和request中
SynchroToken synchroToken = SynchroToken.getInstance();
String token_Key = synchroToken.generateToken(request);
session.setAttribute(ItsConstants.TRANSACTION_TOKEN_KEY,token_Key);
<input type="hidden" name="<%=ItsConstants.REQUEST_TOKEN_KEY %>" value="<%=token_Key %>">
在存放常量的類ItsConstants事先定義2個常量:
/** 處理重複表單提交存放在session中的key name */
public static final String TRANSACTION_TOKEN_KEY = "SS_TOKEN_NAME";
/** 處理重複表單提交存放在REQUEST中的key name */
public static final String REQUEST_TOKEN_KEY = "RQ_TOKEN_NAME";
2、在servlet端進行驗證;
boolean ifDoubleSubmit = SynchroToken.getInstance().isTokenValid(HttpServletRequest, true);
方法isTokenValid()會比較自動獲取session.getAttribute(ItsConstants.TRANSACTION_TOKEN_KEY)和req.getParameter(ItsConstants.REQUEST_TOKEN_KEY)的值並進行比較,該方法的第二個參數“true”表示比較完之後從session中刪除該令牌session.removeAttribute(ItsConstants.TRANSACTION_TOKEN_KEY);
3、類SynchroToken的代碼如下:
package common;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* 利用同步令牌(Token)機制來解決Web應用中重複提交的問題
*
* @author Tony Lin
* @since 2008-9-9
* @version 1.0
* @see Struts中的TokenProcessor類
*/
public class SynchroToken {
/**
* The singleton instance of this class.
*/
private static SynchroToken instance = new SynchroToken();
/**
* Retrieves the singleton instance of this class.
*/
public static SynchroToken getInstance() {
return instance;
}
/**
* Protected constructor for TokenProcessor. Use TokenProcessor.getInstance()
* to obtain a reference to the processor.
*/
protected SynchroToken() {
super();
}
/**
* Return <code>true</code> if there is a transaction token stored in
* the user's current session, and the value submitted as a request
* parameter with this action matches it. Returns <code>false</code>
* under any of the following circumstances:
* <ul>
* <li>No session associated with this request</li>
* <li>No transaction token saved in the session</li>
* <li>No transaction token included as a request parameter</li>
* <li>The included transaction token value does not match the
* transaction token in the user's session</li>
* </ul>
*
* @param request The servlet request we are processing
*/
public synchronized boolean isTokenValid(HttpServletRequest request) {
return this.isTokenValid(request, false);
}
/**
* Return <code>true</code> if there is a transaction token stored in
* the user's current session, and the value submitted as a request
* parameter with this action matches it. Returns <code>false</code>
* <ul>
* <li>No session associated with this request</li>
* <li>No transaction token saved in the session</li>
* <li>No transaction token included as a request parameter</li>
* <li>The included transaction token value does not match the
* transaction token in the user's session</li>
* </ul>
*
* @param request The servlet request we are processing
* @param reset Should we reset the token after checking it?
*/
public synchronized boolean isTokenValid(
HttpServletRequest request,
boolean reset) {
// Retrieve the current session for this request
HttpSession session = request.getSession(false);
if (session == null) {
return false;
}
// Retrieve the transaction token from this session, and
// reset it if requested
String saved = (String) session.getAttribute(ItsConstants.TRANSACTION_TOKEN_KEY);
if (saved == null) {
return false;
}
if (reset) {
this.resetToken(request);
}
// Retrieve the transaction token included in this request
String token = request.getParameter(ItsConstants.REQUEST_TOKEN_KEY);
if (token == null) {
return false;
}
return saved.equals(token);
}
/**
* Reset the saved transaction token in the user's session. This
* indicates that transactional token checking will not be needed
* on the next request that is submitted.
*
* @param request The servlet request we are processing
*/
public synchronized void resetToken(HttpServletRequest request) {
HttpSession session = request.getSession(false);
if (session == null) {
return;
}
session.removeAttribute(ItsConstants.TRANSACTION_TOKEN_KEY);
}
/**
* Save a new transaction token in the user's current session, creating
* a new session if necessary.
*
* @param request The servlet request we are processing
*/
public synchronized void saveToken(HttpServletRequest request) {
HttpSession session = request.getSession();
String token = generateToken(request);
if (token != null) {
session.setAttribute(ItsConstants.TRANSACTION_TOKEN_KEY, token);
}
}
/**
* Generate a new transaction token, to be used for enforcing a single
* request for a particular transaction.
*
* @param request The request we are processing
*/
public String generateToken(HttpServletRequest request) {
HttpSession session = request.getSession();
try {
byte id[] = session.getId().getBytes();
byte now[] = new Long(System.currentTimeMillis()).toString().getBytes();
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(id);
md.update(now);
return this.toHex(md.digest());
} catch (IllegalStateException e) {
return null;
} catch (NoSuchAlgorithmException e) {
return null;
}
}
/**
* Convert a byte array to a String of hexadecimal digits and return it.
*<p>
*<strong>WARNING</strong>: This method is not part of TokenProcessor's
*public API. It's provided for backward compatibility only.
*</p>
* @param buffer The byte array to be converted
*/
public String toHex(byte buffer[]) {
StringBuffer sb = new StringBuffer();
String s = null;
for (int i = 0; i < buffer.length; i++) {
s = Integer.toHexString((int) buffer[i] & 0xff);
if (s.length() < 2) {
sb.append('0');
}
sb.append(s);
}
return sb.toString();
}
}
版權聲明:本文爲博主原創文章,未經博主允許不得轉載。