importjavax.servlet.http.HttpSession;
publicclassToken{
privatestaticfinalStringTOKEN_LIST_NAME="tokenList";
publicstaticfinalStringTOKEN_STRING_NAME="token";
privatestaticArrayListgetTokenList(HttpSessionsession){
Objectobj=session.getAttribute(TOKEN_LIST_NAME);
if(obj!=null){
return(ArrayList)obj;
}else{
ArrayListtokenList=newArrayList();
session.setAttribute(TOKEN_LIST_NAME,tokenList);
returntokenList;
}
}
privatestaticvoidsaveTokenString(StringtokenStr,HttpSessionsession){
ArrayListtokenList=getTokenList(session);
tokenList.add(tokenStr);
session.setAttribute(TOKEN_LIST_NAME,tokenList);
}
privatestaticStringgenerateTokenString(){
returnnewLong(System.currentTimeMillis()).toString();
}
publicstaticStringgetTokenString(HttpSessionsession){
StringtokenStr=generateTokenString();
saveTokenString(tokenStr,session);
returntokenStr;
}
publicstaticbooleanisTokenStringValid(StringtokenStr,HttpSessionsession){
booleanvalid=false;
if(session!=null){
ArrayListtokenList=getTokenList(session);
if(tokenList.contains(tokenStr)){
valid=true;
tokenList.remove(tokenStr);
}
}
returnvalid;
}
}
怎么使用?
在jsp页面端。
首先import该类:
<%@ page import="com.paizuo.framework.util.Token"%>
表单包含隐藏的token字符串:
<form><inputtype="hidden"name="<%=Token.TOKEN_STRING_NAME%>"value="<%=Token.getTokenString(session)%>">
</form>
在Server端action中进行检验。
if(Token.isTokenStringValid(request.getParameter(Token.TOKEN_STRING_NAME),request.getSession())){//进行正常业务流程
}
else{
//进行防重复提交处理流程
}