struts2 下分布式web环境Token改造

最近在看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"

   可以在国际化资源文件中设置中文

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值