springMVC中基于token防止表單重復(fù)提交方法
本文介紹了springMVC中基于token防止表單重復(fù)提交方法,分享給大家,具體如下:
實(shí)現(xiàn)思路:
在springmvc配置文件中加入攔截器的配置,攔截兩類請(qǐng)求,一類是到頁(yè)面的,一類是提交表單的。當(dāng)轉(zhuǎn)到頁(yè)面的請(qǐng)求到來(lái)時(shí),生成token的名字和token值,一份放到Redis緩存中,一份放傳給頁(yè)面表單的隱藏域。(注:這里之所以使用redis緩存,是因?yàn)閠omcat服務(wù)器是集群部署的,要保證token的存儲(chǔ)介質(zhì)是全局線程安全的,而redis是單線程的)
當(dāng)表單請(qǐng)求提交時(shí),攔截器得到參數(shù)中的tokenName和token,然后到緩存中去取token值,如果能匹配上,請(qǐng)求就通過(guò),不能匹配上就不通過(guò)。這里的tokenName生成時(shí)也是隨機(jī)的,每次請(qǐng)求都不一樣。而從緩存中取token值時(shí),會(huì)立即將其刪除(刪與讀是原子的,無(wú)線程安全問(wèn)題)。
實(shí)現(xiàn)方式:
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驗(yàn)證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("未通過(guò)驗(yàn)證..."); return handleInvalidToken(request, response, handler); } } System.out.println("通過(guò)驗(yàn)證..."); return handleValidToken(request, response, handler); } /** * 當(dāng)出現(xiàn)一個(gè)非法令牌時(shí)調(diào)用 */ 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", "請(qǐng)不要頻繁操作!"); writeMessageUtf8(response, data); return false; } /** * 當(dāng)發(fā)現(xiàn)一個(gè)合法令牌時(shí)調(diào)用. */ 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值的默認(rèn)命名空間 */ 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;// 緩存調(diào)用,代替session,支持分布式 public static void setRedisCacheClient(IRedisCacheClient redisCacheClient) { TokenHelper.redisCacheClient = redisCacheClient; } /** * 使用隨機(jī)字串作為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; } /** * 保存一個(gè)給定名字和值的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); } } /** * 構(gòu)建一個(gè)基于token名字的帶有命名空間為前綴的token名字 * * @param tokenName * @return the name space prefixed session token name */ public static String buildTokenCacheAttributeName(String tokenName) { return TOKEN_NAMESPACE + "." + tokenName; } /** * 從請(qǐng)求域中獲取給定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; } /** * 從請(qǐng)求參數(shù)中獲取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; } /** * 驗(yàn)證當(dāng)前請(qǐng)求參數(shù)中的token是否合法,如果合法的token出現(xiàn)就會(huì)刪除它,它不會(huì)再次成功合法的token * * @return 驗(yàn)證結(jié)果 */ 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中加如下內(nèi)容:
<input type="hidden" name="<%=request.getAttribute("xxx.token.name") %>" value="<%=token %>"/> <input type="hidden" name="xxx.token.name" value="<%=request.getAttribute("xxx.token.name") %>"/>
當(dāng)前這里也可以用類似于struts2的自定義標(biāo)簽來(lái)做。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java?Float?保留小數(shù)位精度的實(shí)現(xiàn)
這篇文章主要介紹了Java?Float?保留小數(shù)位精度的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12Intellij IDEA 2017新特性之Spring Boot相關(guān)特征介紹
Intellij IDEA 2017.2.2版本針對(duì)Springboot設(shè)置了一些特性,本篇文章給大家簡(jiǎn)單介紹一下如何使用這些特性,需要的朋友參考下吧2018-01-01解決IntelliJ IDEA創(chuàng)建spring boot無(wú)法連接http://start.spring.io/問(wèn)題
這篇文章主要介紹了解決IntelliJ IDEA創(chuàng)建spring boot無(wú)法連接http://start.spring.io/問(wèn)題,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08MyBatis中常見(jiàn)的SQL執(zhí)行方式及其使用方法
MyBatis可能很多人都一直在用,但是MyBatis的SQL執(zhí)行流程可能并不是所有人都清楚了,下面這篇文章主要給大家介紹了關(guān)于MyBatis中常見(jiàn)的SQL執(zhí)行方式及其使用的相關(guān)資料,需要的朋友可以參考下2023-09-09Springboot?接口需要接收參數(shù)類型是數(shù)組問(wèn)題
這篇文章主要介紹了Springboot?接口需要接收參數(shù)類型是數(shù)組問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-01-01JAVA導(dǎo)出EXCEL表格的實(shí)例教學(xué)
在本文中我們給大家整理了關(guān)于JAVA導(dǎo)出EXCEL表格的實(shí)例教學(xué)以及相關(guān)知識(shí)點(diǎn),需要的朋友們學(xué)習(xí)下。2019-02-02