读书人

struts2 停分布式web环境Token改造

发布时间: 2013-03-26 09:54:34 作者: rapoo

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"

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

?

?

1 楼 xvm03 2011-01-24 有个问题咨询一下,token是基于session保存的,两个页面都使用了token,不会后加载的页面生成的token把先加载的token值给替换掉吗,我看了一些资料tokenname好像是个固定的字符串,struts.token 2 楼 锅巴49 2011-01-25 xvm03 写道有个问题咨询一下,token是基于session保存的,两个页面都使用了token,不会后加载的页面生成的token把先加载的token值给替换掉吗,我看了一些资料tokenname好像是个固定的字符串,struts.token
token是在session中的,两个页面的token不会一样 3 楼 xvm03 2011-01-25 锅巴49 写道xvm03 写道有个问题咨询一下,token是基于session保存的,两个页面都使用了token,不会后加载的页面生成的token把先加载的token值给替换掉吗,我看了一些资料tokenname好像是个固定的字符串,struts.token
token是在session中的,两个页面的token不会一样

token 是struts2标签设置到到session里的一个随机数值,但是name=struts.token不就会相互替换了吗,每个页面生成的token值是不一样的,但是在保存到session时,如果名称一样不就会被替换了?服务端是怎样区分的呢?这块我觉得名称也是随机的跟request相关,可是源代码里查看到的都是struts.token,很不理解是为什么? 4 楼 锅巴49 2011-01-26 xvm03 写道有个问题咨询一下,token是基于session保存的,两个页面都使用了token,不会后加载的页面生成的token把先加载的token值给替换掉吗,我看了一些资料tokenname好像是个固定的字符串,struts.token
不会,每次生成的token值都不一样.

读书人网 >Web前端

热点推荐