在Spring Boot中,可以使用Token令牌的方式来防止短时间内的重复提交。以下是一种实现方式:

  1. 在Controller方法中添加一个令牌生成和验证的逻辑。
@Controller
public class MyController {
  
  private static final Map<String, Boolean> tokenMap = new ConcurrentHashMap<>();
  
  @PostMapping("/submit")
  public String submitForm(@RequestParam("token") String token, Model model) {
    if (tokenMap.containsKey(token)) {
      // 令牌已存在,说明是重复提交
      model.addAttribute("message", "请勿重复提交表单");
      return "error";
    } else {
      // 令牌不存在,将其添加到令牌Map中
      tokenMap.put(token, true);
      // 处理表单提交逻辑
      // ...
      // 提交完成后,需要移除令牌
      tokenMap.remove(token);
      return "success";
    }
  }
  
  @ModelAttribute("token")
  public String generateToken() {
    // 生成令牌,并将其添加到Model中,用于在表单中传递
    String token = UUID.randomUUID().toString();
    tokenMap.put(token, true);
    return token;
  }
}
  1. 在表单页面中,需要添加一个隐藏的input字段来传递令牌。
<form action="/submit" method="post">
  <input type="hidden" name="token" value="${token}" />
  <!-- 其他表单字段 -->
  <button type="submit">提交</button>
</form>

这样,每次请求提交表单时,都会生成一个唯一的令牌,并将其添加到令牌Map中。如果重复提交同一个令牌,即可判断为重复提交。在提交完成后,需要及时从令牌Map中移除对应的令牌。

需要注意的是,这种方式只能防止短时间内的重复提交,并不能完全保证数据的一致性。在复杂的场景下,可能需要结合其他机制来保证数据的一致性,例如使用数据库的唯一索引、悲观锁或乐观锁等

标签: 汽车


原文地址: https://cveoy.top/t/topic/iaKY 著作权归作者所有。请勿转载和采集!