禁止重复提交的目的是担保数据准确性及安全性的必要操作。
2.案例当注册用户时,用户在2秒内,多次提交。则认为重复提交。利用ssm+redis实现该防止重复注册功能
3.开拓自定义表明类/ 防重复提交的自定义表明/@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface ForRepeatCommit {String value() default 34;";}
4.开拓切面类
用来在参数进行业务操作前,验证是否为重复提交。这个切面对标注@ForRepeatCommit表明的方法进行切入。
@Aspect@Componentpublic class ForRepearCommitAop {@AutowiredCheckTokenService checkTokenService;//提交提高行校验@Before(value="@annotation(com.bobo.util.ForRepeatCommit)")public void valid(){ServletRequestAttributes requestAttributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();HttpServletRequest request = requestAttributes.getRequest();//用户要求sessionid和要求地址当做唯一的keyString key=requestAttributes.getSessionId()+"-"+request.getServletPath();//调用校验keycheckTokenService.checkSessionIdAndUrl(key);}}
5.开拓验证是否重复提交的Service5.1 接口
public interface CheckTokenService {void checkSessionIdAndUrl(String key);}
5.2 实现类
@Servicepublic class CheckTokenServiceImpl implements CheckTokenService {@AutowiredRedisTemplate redisTemplate;@Overridepublic void checkSessionIdAndUrl(String key) {if(StringUtils.isEmpty(key)){throw new RuntimeException("key is null");//key null}//如果redis没有该key ,则粗惹存入redis并且设置超时时间2秒if(redisTemplate.opsForValue().get(key)==null){redisTemplate.opsForValue().set(key,key,2, TimeUnit.SECONDS);}else{throw new RuntimeException("repeat commit ");//重复提交}}}
6.controller
@Controllerpublic class UserController {@AutowiredUserService userService;@GetMapping("add")//跳转到增加页面public String add(){return "add";}@ForRepeatCommit //标记为防重复提交表明@PostMapping("add")//实行注册public String add(User user){int i = userService.add(user);if(i>0)return "success";return "fail";}}
7.jsp
<body><form action="add" method="post">用户名:<input type="text" name="name"><br>密 码:<input type="password" name="pwd"><br><button type="submit">提交</button></form></body>
8.效果展示8.1正常提交
在两秒内多次提交