springmvc下的基于token的防重复提交 - 高飞网
236 人阅读

springmvc下的基于token的防重复提交

2015-12-12 14:42:54

问题描述:

现在的网站在注册步骤中,由于后台要处理大量信息,造成响应变慢(测试机器性能差也是造成变慢的一个因素),在前端页面提交信息之前,等待后端响应,此时如果用户
再点一次提交按钮,后台会保存多份用户信息。为解决此问题,借鉴了struts2的token思路,在springmvc下实现token。

实现思路:

在springmvc配置文件中加入拦截器的配置,拦截两类请求,一类是到页面的,一类是提交表单的。当转到页面的请求到来时,生成token的名字和token值,一份放到redis缓存中,一份放传给页面表单的隐藏域。(注:这里之所以使用redis缓存,是因为tomcat服务器是集群部署的,要保证token的存储介质是全局线程安全的,而redis是单线程的)

当表单请求提交时,拦截器得到参数中的tokenName和token,然后到缓存中去取token值,如果能匹配上,请求就通过,不能匹配上就不通过。这里的tokenName生成时也是随机的,每次请求都不一样。而从缓存中取token值时,会立即将其删除(删与读是原子的,无线程安全问题)。

实现方式:


import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.xxx.cache.redis.IRedisCacheClient;
import com.xxx.common.utility.JsonUtil;
import com.xxx.www.common.utils.TokenHelper;

/**
 * 
 * @see TokenHelper
 */
public class TokenInterceptor extends HandlerInterceptorAdapter {

    private static Logger log = Logger.getLogger(TokenInterceptor.class);
    private static Map<String, String> viewUrls = new HashMap<String, String>();
    private static Map<String, String> actionUrls = new HashMap<String, String>();
    private Object clock = new Object();

    @Autowired
    private IRedisCacheClient redisCacheClient;
    static {
        viewUrls.put("/user/regc/brandregnamecard/", "GET");
        viewUrls.put("/user/regc/regnamecard/", "GET");

        actionUrls.put("/user/regc/brandregnamecard/", "POST");
        actionUrls.put("/user/regc/regnamecard/", "POST");
    }
    {
        TokenHelper.setRedisCacheClient(redisCacheClient);
    }

    /**
     * 拦截方法,添加or验证token
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI();
        String method = request.getMethod();
        if (viewUrls.keySet().contains(url) && ((viewUrls.get(url)) == null || viewUrls.get(url).equals(method))) {
            TokenHelper.setToken(request);
            return true;
        } else if (actionUrls.keySet().contains(url)
                && ((actionUrls.get(url)) == null || actionUrls.get(url).equals(method))) {
            log.debug("Intercepting invocation to check for valid transaction token.");
            return handleToken(request, response, handler);
        }
        return true;
    }

    protected boolean handleToken(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        synchronized (clock) {
            if (!TokenHelper.validToken(request)) {
                System.out.println("未通过验证...");
                return handleInvalidToken(request, response, handler);
            }
        }
        System.out.println("通过验证...");
        return handleValidToken(request, response, handler);
    }

    /**
     * 当出现一个非法令牌时调用
     */
    protected boolean handleInvalidToken(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("flag", 0);
        data.put("msg", "请不要频繁操作!");
        writeMessageUtf8(response, data);
        return false;
    }

    /**
     * 当发现一个合法令牌时调用.
     */
    protected boolean handleValidToken(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        return true;
    }

    private void writeMessageUtf8(HttpServletResponse response, Map<String, Object> json) throws IOException {
        try {
            response.setCharacterEncoding("UTF-8");
            response.getWriter().print(JsonUtil.toJson(json));
        } finally {
            response.getWriter().close();
        }
    }

}


还没有评论!
54.146.5.196