springmvc 防止表单重复提交的两种方法
作者:阿豪_mike 时间:2023-03-27 17:57:18
目录
1、通过session中的token验证
步骤1:创建自定义注解
步骤2:创建自定义 * (@slf4j是lombok的注解)
步骤3:将自定义 * 添加到配置文件
2、通过当前用户上一次请求的url和参数验证重复提交
步骤1:创建自定义注解
步骤2:创建自定义 *
步骤3:将自定义 * 添加到配置文件
最近在本地开发测试的时候,遇到一个表单重复提交的现象。 因为网络延迟的问题,我点击了两次提交按钮,数据库里生成了两条记录。其实这种现象以前也有遇到过,一般都是提交后把按钮置灰,无法再次提交,这是很常见的客户端处理的方式。 但是这不是从根本上解决问题,虽然客户端解决了多次提交的问题,但是接口中依旧存在着问题。假设我们不是从客户端提交,而是被其他的系统调用,当遇到网络延迟,系统补偿的时候,还会遇到这种问题
1、通过session中的token验证
初始化页面时生成一个唯一token,将其放在页面隐藏域和session中
* 拦截请求,校验来自页面请求中的token与session中的token是否一致
判断,如果一致则提交成功并移除session中的token,不一致则说明重复提交并记录日志
步骤1:创建自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Token {
boolean save() default false;
boolean remove() default false;
}
步骤2:创建自定义 * (@slf4j是lombok的注解)
@Slf4j
public class RepeatSubmitInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
HandlerMethod handlerMethod = null;
try {
handlerMethod = (HandlerMethod)handler;
} catch (Exception e) {
return true;
}
Method method = handlerMethod.getMethod();
Token token = method.getAnnotation(Token.class);
if(token != null ){
boolean saveSession = token.save();
if(saveSession){
request.getSession(true).setAttribute("token", UUID.randomUUID());
}
boolean removeSession = token.remove();
if(removeSession){
if(isRepeatSubmitSession(request)){
log.info("repeat submit session :" + request.getServletPath());
response.sendRedirect("/error/409");
return false;
}
request.getSession(true).removeAttribute("token");
}
}
return true;
}
private boolean isRepeatSubmitSession(HttpServletRequest request){
String sessionToken = String.valueOf(request.getSession(true).getAttribute("token") == null ? "" : request.getSession(true).getAttribute("token"));
String clientToken = String.valueOf(request.getParameter("token") == null ? "" : request.getParameter("token"));
if(sessionToken == null || sessionToken.equals("")){
return true;
}
if(clientToken == null || clientToken.equals("")){
return true;
}
if(!sessionToken.equals(clientToken)){
return true;
}
return false;
}
}
步骤3:将自定义 * 添加到配置文件
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.chinagdn.base.common.interceptor.RepeatSubmitInterceptor"/>
</mvc:interceptor>
使用案例
//save = true 用于生成token
@Token(save = true)
@RequestMapping(value = "save", method = RequestMethod.GET)
public String save(LoginUser loginUser, Model model) throws Exception {
return "sys/user/edit";
}
//remove = true 用于验证token
@Token(remove = true)
@RequestMapping(value = "save", method = RequestMethod.POST)
public String save(@Valid LoginUser loginUser, Errors errors, RedirectAttributes redirectAttributes, Model model) throws Exception {
//.....
}
jsp页面隐藏域添加token
<input type="hidden" name="token" value="${sessionScope.token}">
2、通过当前用户上一次请求的url和参数验证重复提交
* 拦截请求,将上一次请求的url和参数和这次的对比
判断,是否一致说明重复提交并记录日志
步骤1:创建自定义注解
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface SameUrlData {
}
步骤2:创建自定义 *
public class SameUrlDataInterceptor extends HandlerInterceptorAdapter {
@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 注解
SameUrlData annotation = method.getAnnotation(SameUrlData.class);
if (annotation != null) {
if (repeatDataValidator(request)) {//如果重复相同数据
response.sendRedirect("/error/409");
return false;
} else {
return true;
}
}
return true;
} else {
return super.preHandle(request, response, handler);
}
}
/**
* 验证同一个url数据是否相同提交 ,相同返回true
* @param httpServletRequest
* @return
*/
private boolean repeatDataValidator(HttpServletRequest httpServletRequest) {
String params = JsonMapper.toJsonString(httpServletRequest.getParameterMap());
String url = httpServletRequest.getRequestURI();
Map<String, String> map = new HashMap<>();
map.put(url, params);
String nowUrlParams = map.toString();//
Object preUrlParams = httpServletRequest.getSession().getAttribute("repeatData");
if (preUrlParams == null) { //如果上一个数据为null,表示还没有访问页面
httpServletRequest.getSession().setAttribute("repeatData", nowUrlParams);
return false;
} else { //否则,已经访问过页面
if (preUrlParams.toString().equals(nowUrlParams)) { //如果上次url+数据和本次url+数据相同,则表示城府添加数据
return true;
} else { //如果上次 url+数据 和本次url加数据不同,则不是重复提交
httpServletRequest.getSession().setAttribute("repeatData", nowUrlParams);
return false;
}
}
}
}
步骤3:将自定义 * 添加到配置文件
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.chinagdn.base.common.interceptor.SameUrlDataInterceptor"/>
</mvc:interceptor>
使用案例
//在controller层使用 @SameUrlData 注解即可
@SameUrlData
@RequestMapping(value = "save", method = RequestMethod.POST)
public String save(@Valid LoginUser loginUser, Errors errors, RedirectAttributes redirectAttributes, Model model) throws Exception {
//.....
}
来源:https://juejin.cn/post/6990963223486791688
标签:springmvc,表单,重复提交
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
关于MyBatis中SqlSessionFactory和SqlSession简解
2022-02-18 13:57:37
Java发送邮件遇到的常见需求汇总
2021-10-07 14:51:02
详解Java编程的Observer观察者设计模式
2023-11-10 04:06:07
Java最简洁数据结构之冒泡排序快速理解
2023-12-01 06:31:52
![](https://img.aspxhome.com/file/2023/8/60278_0s.png)
Spring Boot 整合 Apache Dubbo的示例代码
2021-10-09 03:52:07
![](https://img.aspxhome.com/file/2023/8/60488_0s.jpg)
Spring(AbstractRoutingDataSource)实现动态数据源切换示例
2022-05-23 07:05:08
![](https://img.aspxhome.com/file/2023/1/64111_0s.jpg)
Mybatis常用分页插件实现快速分页处理技巧
2022-12-25 00:03:45
Studio 编译报错:compileSdkVersion 'android-24' requires JDK 1.8 or later to compile.的解决办法
2023-06-19 17:19:41
![](https://img.aspxhome.com/file/2023/0/81320_0s.png)
深入解析Java并发程序中线程的同步与线程锁的使用
2022-03-19 10:25:38
![](https://img.aspxhome.com/file/2023/1/65621_0s.jpg)
Java 线程的优先级(setPriority)案例详解
2023-11-12 23:46:39
![](https://img.aspxhome.com/file/2023/8/59168_0s.png)
IDEA社区版下载安装流程详解(小白篇)
2021-11-13 12:37:18
![](https://img.aspxhome.com/file/2023/4/61684_0s.png)
FeignClient中name和url属性的作用说明
2023-06-04 13:21:55
解决SpringBoot中MultipartResolver和ServletFileUpload的冲突问题
2023-10-22 15:28:19
![](https://img.aspxhome.com/file/2023/1/60841_0s.png)
深入剖析构建JSON字符串的三种方式(推荐)
2023-09-26 07:47:22
![](https://img.aspxhome.com/file/2023/6/68696_0s.png)
如何创建SpringBoot项目
2022-03-26 16:06:37
![](https://img.aspxhome.com/file/2023/7/68167_0s.png)
Java中Request请求转发详解
2021-05-25 20:53:42
![](https://img.aspxhome.com/file/2023/8/61538_0s.png)
Java spring webmvc如何实现控制反转
2023-03-12 06:35:56
Java中避免过多if-else的几种方法
2023-11-28 13:07:09
c#和java base64不一致的解决方法
2022-11-24 02:18:55
![](https://img.aspxhome.com/file/2023/0/68740_0s.png)
flutter日期选择器 flutter时间选择器
2023-09-22 04:50:15
![](https://img.aspxhome.com/file/2023/8/90158_0s.jpg)