最近在看struts2源码,发现struts2下的token拦截是基于session的
核心类是org.apache.struts2.util.TokenHelper
在页面上用标签打入token标记
public static String setToken(String tokenName) {
Map session = ActionContext.getContext().getSession();
String token = generateGUID();
try {
session.put(tokenName, token);
}
catch(IllegalStateException e) {
// WW-1182 explain to user what the problem is
String msg = "Error creating HttpSession due response is commited to client. You can use the CreateSessionInterceptor or create the HttpSession from your action before the result is rendered to the client: " + e.getMessage();
LOG.error(msg, e);
throw new IllegalArgumentException(msg);
}
return token;
}
可以看到,是生成一段随机码放入页面,同时也置入session。
请求提交时,在org.apache.struts2.interceptor.TokenInterceptor
protected String doIntercept(ActionInvocation invocation) throws Exception {
if (log.isDebugEnabled()) {
log.debug("Intercepting invocation to check for valid transaction token.");
}
Map session = ActionContext.getContext().getSession();
synchronized (session) {
if (!TokenHelper.validToken()) {
return handleInvalidToken(invocation);
}
return handleValidToken(invocation);
}
}
public static boolean validToken() {
String tokenName = getTokenName();
if (tokenName == null) {
if (LOG.isDebugEnabled())
LOG.debug("no token name found -> Invalid token ");
return false;
}
String token = getToken(tokenName);
if (token == null) {
if (LOG.isDebugEnabled())
LOG.debug("no token found for token name "+tokenName+" -> Invalid token ");
return false;
}
Map session = ActionContext.getContext().getSession();
String sessionToken = (String) session.get(tokenName);
if (!token.equals(sessionToken)) {
LOG.warn(LocalizedTextUtil.findText(TokenHelper.class, "struts.internal.invalid.token", ActionContext.getContext().getLocale(), "Form token {0} does not match the session token {1}.", new Object[]{
token, sessionToken
}));
return false;
}
// remove the token so it won't be used again
session.remove(tokenName);
return true;
}
这样当多台应用不复制session时,就会有问题。
我改造了下,把token放入分布式共享缓存中,保持web服务无状态。
需要新建
1、新建MyTokenHelper
/**
*
* token 操作
*
* @author 锅巴
* @version 1.0 2010-7-22
*/
public class MyTokenHelper extends TokenHelper{
//分布式缓存服务
static ICacheService cacheService = null;
private static ICacheService getCacheService(){
if(cacheService == null){
cacheService = (ICacheService)ContentUtil.getBean("cacheService");
}
return cacheService;
}
public static String setToken() {
String token = generateGUID();
getCacheService().setValue(token, "1");
return token;
}
public static boolean validToken() {
String token = getToken(DEFAULT_TOKEN_NAME);
if (token == null) {
return false;
}
if(getCacheService().getValue(token) == null){
return false;
}
getCacheService().remove(token);
return true;
}
public static void main(String[] args) {
System.out.println(MyTokenHelper.setToken(""));
}
}
2、新建MyTokenInterceptor拦截器
/**
*
* token 拦截器
*
* @author 锅巴
* @version 1.0 2010-7-22
*/
public class MyTokenInterceptor extends TokenInterceptor{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
protected String doIntercept(ActionInvocation invocation) throws Exception {
if (!MyTokenHelper.validToken()) {
return handleInvalidToken(invocation);
}
return handleValidToken(invocation);
}
}
3、新建MyTokenTag JSP 标签,用于生成token标记
/**
*
* token tag
*
* @author 锅巴
* @version 1.0 2010-7-22
*/
public class MyTokenTag extends TagSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
public int doStartTag()throws JspException {
JspWriter out=pageContext.getOut();
try{
out.println("<input type=\"hidden\" name=\"" + MyTokenHelper.DEFAULT_TOKEN_NAME + "\" value=\"" + MyTokenHelper.setToken() + "\"/>");
}catch(IOException e){
throw new JspException(e);
}
return SKIP_BODY;
}
4、新建mytag.tld
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
<tlib-version>1.6</tlib-version>
<jsp-version>1.2</jsp-version>
<short-name>mytag</short-name>
<description>mytag</description>
<uri>/</uri>
<tag>
<name>token</name>
<tagclass>com.my.tag.MyTokenTag</tagclass>
</tag>
</taglib>
5、在页面中使用
<%@taglib uri="/WEB-INF/mytag.tld" prefix="mytag"%>
<mytag:token/>
6、在POST action 配置
<interceptor-ref name="myToken"/>
<result name="invalid.token" type="dispatcher">
/file_up.jsp
</result>
当验证不通过时,会向actionError加入错误提醒,键值是"struts.messages.invalid.token"
可以在国际化资源文件中设置中文