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配置中注册拦截器。