springboot前后端分离使用注解进行防重
使用redis缓存,使用时带入依赖,
这里使用的是前后端分离,使用注解在controller层方法上使用@SameUrlData 注解
在拦截器里面进行判断,是否此请求需要进行防重判断,判断方法为
1.有参请求,
2.无参请求,
使用 StringRedisTemplate 类进行存储和获取 判断
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- SameUrlData 注解类
- SameUrlDataInterceptor 防重拦截器
- WebMvcConfigExt 添加拦截器
SameUrlData
package com.eaos.util.same;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Description: 自定义注解防止表单重复提交
*/
@Inherited
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SameUrlData {
}
SameUrlDataInterceptor
这个拦截器没有考虑到Restfu风格的请求
可以自己进行设置修改
package com.eaos.util.same;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import com.alibaba.fastjson.JSONObject;
import com.eaos.util.common.RedisConfig;
/**
* @Title: 防止用户重复提交数据拦截器
* @Description: 将用户访问的url和参数结合token存入redis,每次访问进行验证是否重复请求接口
*/
@Component
public class SameUrlDataInterceptor extends HandlerInterceptorAdapter {
@Autowired
StringRedisTemplate smsRedisTemplate;
private static Logger LOG = LoggerFactory.getLogger(SameUrlDataInterceptor.class);
/**
* 是否阻止提交,fasle阻止,true放行
* @return
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Method method = handlerMethod.getMethod();
SameUrlData annotation = method.getAnnotation(SameUrlData.class);
if (annotation != null) {
if(repeatDataValidator(request)){
//请求数据相同
LOG.warn("please don't repeat submit,url:"+ request.getServletPath());
//前后端分离使用respone返回参数
JSONObject result = new JSONObject();
result.put("code","500");
result.put("msg","请勿重复请求");
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
response.getWriter().write(result.toString());
response.getWriter().close();
//如果不是前后端分离可以进行页面转发
// 拦截之后跳转页面
// String formRequest = request.getRequestURI();
// request.setAttribute("myurl", formRequest);
// request.getRequestDispatcher("/WebRoot/common/error/jsp/error_message.jsp").forward(request, response);
return false;
}else {//如果不是重复相同数据
return true;
}
}
return true;
} else {
return super.preHandle(request, response, handler);
}
}
/**
* 验证同一个url数据是否相同提交,相同返回true
* @param httpServletRequest
* @return
*/
public boolean repeatDataValidator(HttpServletRequest httpServletRequest){
//获取请求参数map
Map<String, String[]> parameterMap = httpServletRequest.getParameterMap();
Iterator<Map.Entry<String, String[]>> it = parameterMap.entrySet().iterator();
String token = "";
Map<String, String[]> parameterMapNew = new HashMap<>();
while(it.hasNext()){
Map.Entry<String, String[]> entry = it.next();
parameterMapNew.put(entry.getKey(), entry.getValue());
}
//session值可以是固定的
token = httpServletRequest.getSession().getAttribute("JSESSIONID").toString();
if (token.equals("")){
//如果没有token,直接放行
return false;
}
//过滤过后的请求内容
String params = JSONObject.toJSONString(parameterMapNew);
String url = httpServletRequest.getRequestURI();
Map<String,String> map = new HashMap<>();
//key为接口,value为参数
map.put(url, params);
String nowUrlParams = map.toString();
String redisKey = token + url;
String preUrlParams = smsRedisTemplate.opsForValue().get(redisKey);
if(preUrlParams == null){
//如果上一个数据为null,表示还没有访问页面
//存放并且设置有效期,2秒
smsRedisTemplate.opsForValue().set(redisKey, nowUrlParams, 2, TimeUnit.SECONDS);
return false;
}else{//否则,已经访问过页面
if(preUrlParams.equals(nowUrlParams)){
//如果上次url+数据和本次url+数据相同,则表示重复添加数据
return true;
}else{//如果上次 url+数据 和本次url加数据不同,则不是重复提交
smsRedisTemplate.opsForValue().set(redisKey, nowUrlParams, 1, TimeUnit.SECONDS);
return false;
}
}
}
}
WebMvcConfigExt
package com.eaos.util.filter;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.eaos.util.same.SameUrlDataInterceptor;
/**
*拦截器进行配置
*/
@SuppressWarnings("deprecation")
@SpringBootConfiguration
public class SpringMVCConfig extends WebMvcConfigurerAdapter {
/**
* 防止重复提交拦截器
*/
@Autowired
private SameUrlDataInterceptor sameUrlDataInterceptor;
public void addInterceptors(InterceptorRegistry registry) {
// 避开静态资源
List<String> resourcePaths = defineResourcePaths();
//全部进行拦截,也可以自己进行定义拦截,
//addPathPatterns 拦截路劲
//excludePathPatterns 忽略拦截路劲
//registry.addInterceptor(sameUrlDataInterceptor).addPathPatterns("/**");不需要忽略使用
registry.addInterceptor(sameUrlDataInterceptor).addPathPatterns("/**").excludePathPatterns(resourcePaths);// 重复请求
}
/**
* 自定义静态资源路径
*
* @return
*/
public List<String> defineResourcePaths() {
List<String> patterns = new ArrayList<>();
patterns.add("/assets/**");
patterns.add("/upload/**");
patterns.add("/static/**");
patterns.add("/common/**");
patterns.add("/error");
return patterns;
}
}
使用方法
自己在controller类的请求方法上使用@SameUrlData
很简单的一个表单提交防重案例