欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

springMVC中基于token防止表单重复提交方法

程序员文章站 2023-11-18 22:58:10
本文介绍了springmvc中基于token防止表单重复提交方法,分享给大家,具体如下: 实现思路: 在springmvc配置文件中加入拦截器的配置,拦截两类请求,一类...

本文介绍了springmvc中基于token防止表单重复提交方法,分享给大家,具体如下:

实现思路:

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

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

实现方式:

tokeninterceptor.java

package com.xxx.www.common.interceptor; 

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(); 
    } 
  } 

} 

tokenhelper.java

package com.xxx.www.common.utils; 

import java.math.biginteger; 
import java.util.map; 
import java.util.random; 
import javax.servlet.http.httpservletrequest; 
import org.apache.log4j.logger; 
import com.xxx.cache.redis.irediscacheclient; 

/** 
 * tokenhelper 
 * 
 */ 
public class tokenhelper 
{ 

  /** 
   * 保存token值的默认命名空间 
   */ 
  public static final string token_namespace = "xxx.tokens"; 

  /** 
   * 持有token名称的字段名 
   */ 
  public static final string token_name_field = "xxx.token.name"; 
  private static final logger log = logger.getlogger(tokenhelper.class); 
  private static final random random = new random(); 

  private static irediscacheclient rediscacheclient;// 缓存调用,代替session,支持分布式 

  public static void setrediscacheclient(irediscacheclient rediscacheclient) 
  { 
    tokenhelper.rediscacheclient = rediscacheclient; 
  } 

  /** 
   * 使用随机字串作为token名字保存token 
   * 
   * @param request 
   * @return token 
   */ 
  public static string settoken(httpservletrequest request) 
  { 
    return settoken(request, generateguid()); 
  } 

  /** 
   * 使用给定的字串作为token名字保存token 
   * 
   * @param request 
   * @param tokenname 
   * @return token 
   */ 
  private static string settoken(httpservletrequest request, string tokenname) 
  { 
    string token = generateguid(); 
    setcachetoken(request, tokenname, token); 
    return token; 
  } 

  /** 
   * 保存一个给定名字和值的token 
   * 
   * @param request 
   * @param tokenname 
   * @param token 
   */ 
  private static void setcachetoken(httpservletrequest request, string tokenname, string token) 
  { 
    try 
    { 
      string tokenname0 = buildtokencacheattributename(tokenname); 
      rediscacheclient.listlpush(tokenname0, token); 
      request.setattribute(token_name_field, tokenname); 
      request.setattribute(tokenname, token); 
    } 
    catch(illegalstateexception e) 
    { 
      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); 
    } 
  } 

  /** 
   * 构建一个基于token名字的带有命名空间为前缀的token名字 
   * 
   * @param tokenname 
   * @return the name space prefixed session token name 
   */ 
  public static string buildtokencacheattributename(string tokenname) 
  { 
    return token_namespace + "." + tokenname; 
  } 

  /** 
   * 从请求域中获取给定token名字的token值 
   * 
   * @param tokenname 
   * @return the token string or null, if the token could not be found 
   */ 
  public static string gettoken(httpservletrequest request, string tokenname) 
  { 
    if(tokenname == null) 
    { 
      return null; 
    } 
    map params = request.getparametermap(); 
    string[] tokens = (string[]) (string[]) params.get(tokenname); 
    string token; 
    if((tokens == null) || (tokens.length < 1)) 
    { 
      log.warn("could not find token mapped to token name " + tokenname); 
      return null; 
    } 

    token = tokens[0]; 
    return token; 
  } 

  /** 
   * 从请求参数中获取token名字 
   * 
   * @return the token name found in the params, or null if it could not be found 
   */ 
  public static string gettokenname(httpservletrequest request) 
  { 
    map params = request.getparametermap(); 

    if(!params.containskey(token_name_field)) 
    { 
      log.warn("could not find token name in params."); 
      return null; 
    } 

    string[] tokennames = (string[]) params.get(token_name_field); 
    string tokenname; 

    if((tokennames == null) || (tokennames.length < 1)) 
    { 
      log.warn("got a null or empty token name."); 
      return null; 
    } 

    tokenname = tokennames[0]; 

    return tokenname; 
  } 

  /** 
   * 验证当前请求参数中的token是否合法,如果合法的token出现就会删除它,它不会再次成功合法的token 
   * 
   * @return 验证结果 
   */ 
  public static boolean validtoken(httpservletrequest request) 
  { 
    string tokenname = gettokenname(request); 

    if(tokenname == null) 
    { 
      log.debug("no token name found -> invalid token "); 
      return false; 
    } 

    string token = gettoken(request, tokenname); 

    if(token == null) 
    { 
      if(log.isdebugenabled()) 
      { 
        log.debug("no token found for token name " + tokenname + " -> invalid token "); 
      } 
      return false; 
    } 

    string tokencachename = buildtokencacheattributename(tokenname); 
    string cachetoken = rediscacheclient.listlpop(tokencachename); 

    if(!token.equals(cachetoken)) 
    { 
      log.warn("xxx.internal.invalid.token form token " + token + " does not match the session token " + cachetoken + "."); 
      return false; 
    } 

    // remove the token so it won't be used again 

    return true; 
  } 

  public static string generateguid() 
  { 
    return new biginteger(165,random).tostring(36).touppercase(); 
  } 

} 

spring-mvc.xml

<!-- token拦截器--> 
  <bean id="tokeninterceptor" class="com.xxx.www.common.interceptor.tokeninterceptor"></bean>   
  <bean class="org.springframework.web.servlet.mvc.annotation.defaultannotationhandlermapping">   
    <property name="interceptors">   
      <list>   
        <ref bean="tokeninterceptor"/>   
      </list> 
    </property>   
  </bean> 

input.jsp 在form中加如下内容:

<input type="hidden" name="<%=request.getattribute("xxx.token.name") %>" value="<%=token %>"/> 

<input type="hidden" name="xxx.token.name" value="<%=request.getattribute("xxx.token.name") %>"/> 

当前这里也可以用类似于struts2的自定义标签来做。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。