【SpringBoot】4种方式 防止表单重复提交

 

1. 使用重定向

对于POST请求,在处理完表单提交后,服务器应该返回一个302重定向,而不是200 OK。这样,即使用户刷新页面,也会触发GET请求,而不是重复POST请求。这是HTTP协议中所谓的“Post/Redirect/Get”模式。

@GetMapping("/form")
public String showForm(Model model) {
    return "form";
}

@PostMapping("/submit")
public String submitForm(@ModelAttribute("form") YourForm form, BindingResult result) {
    if (result.hasErrors()) {
        return "form";
    }
    // 处理表单逻辑...
    return "redirect:/success";
}

2. 使用Token机制

生成一个唯一的token,每次表单提交时都包含这个token,服务器验证token的有效性,一旦验证成功,就将其标记为已使用或从缓存中删除。

生成和验证Token

在客户端生成一个token,并将其存储在session中,同时在表单中添加一个隐藏字段用于传输token。

// 生成token
@Autowired
private HttpSession session;

public String generateToken() {
    String token = UUID.randomUUID().toString();
    session.setAttribute("token", token);
    return token;
}

// 验证token
public boolean validateToken(String submittedToken) {
    String expectedToken = (String) session.getAttribute("token");
    return Objects.equals(expectedToken, submittedToken);
}

在Controller中使用

@PostMapping("/submit")
public String submitForm(@RequestParam("token") String token, ...) {
    if (!validateToken(token)) {
        // Token无效,可能是重复提交
        throw new RuntimeException("Invalid token");
    }
    // 处理表单逻辑...
    session.removeAttribute("token"); // 清除token
    return "redirect:/success";
}

3. 使用AOP + Redis

可以利用面向切面编程(AOP)和Redis来存储和验证token,这种方法适合分布式环境,因为token存储在共享的Redis数据库中。

@Aspect
@Component
public class DuplicateSubmitAspect {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Before("@annotation(com.example.annotation.NoDuplicateSubmit)")
    public void checkDuplicate(JoinPoint joinPoint) {
        // 获取token并验证
        Object[] args = joinPoint.getArgs();
        HttpServletRequest request = (HttpServletRequest) args[0];
        String token = request.getParameter("token");
        if (redisTemplate.opsForValue().get(token) != null) {
            throw new RuntimeException("Duplicate submit detected");
        }
        redisTemplate.opsForValue().set(token, "true", 30, TimeUnit.MINUTES); // 存储token
    }

    @AfterReturning(pointcut = "@annotation(com.example.annotation.NoDuplicateSubmit)", returning = "retVal")
    public void clearToken(JoinPoint joinPoint, Object retVal) {
        Object[] args = joinPoint.getArgs();
        HttpServletRequest request = (HttpServletRequest) args[0];
        String token = request.getParameter("token");
        redisTemplate.delete(token); // 清除token
    }
}

4. 使用拦截器

可以创建一个拦截器来检查重复提交,类似于使用token的机制,但是更灵活。

@Component
public class DuplicateSubmitInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在这里检查和验证token
        return true; // 如果验证失败,返回false
    }
}

确保在Spring配置中注册拦截器。

 

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值