这里介绍是通过redis+token 来实现防止重复提交问题。
1. pom文件依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.1.1</version>
</dependency>
<!-- mysql 依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- SpringBoot 对lombok 支持 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!-- SpringBoot web 核心组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<!-- SpringBoot 外部tomcat支持 -->
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- springboot-log4j -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>
<!-- springboot-aop 技术 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-lang/commons-lang -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
2. redis 的访问类如下:
package com.hou.utils;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
@Component
public class BaseRedisService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
public void setString(String key, Object data, Long timeout) {
if (data instanceof String) {
String value = (String) data;
stringRedisTemplate.opsForValue().set(key, value);
}
if (timeout != null) {
stringRedisTemplate.expire(key, timeout, TimeUnit.SECONDS);
}
}
public Object getString(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
public void delKey(String key) {
stringRedisTemplate.delete(key);
}
}
3. redis token 类操作:
/**
* 功能说明:
* 功能作者:
* 创建日期:
*/
package com.hou.utils;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
// 如何生成token
@Component
public class RedisToken {
@Autowired
private BaseRedisService baseRedisService;
private static final long TOKENTIMEOUT = 60 * 60;
public String getToken() {
// 生成token 规则保证 临时且唯一 不支持分布式场景 分布式全局ID生成规则
String token = "token" + UUID.randomUUID();
// 如何保证token临时 (缓存)使用redis 实现缓存
baseRedisService.setString(token, token, TOKENTIMEOUT);
return token;
}
// 1.在调用接口之前生成对应的令牌(Token), 存放在Redis
// 2.调用接口的时候,将该令牌放入的请求头中
// 3.接口获取对应的令牌,如果能够获取该令牌(将当前令牌删除掉) 就直接执行该访问的业务逻辑
// 4.接口获取对应的令牌,如果获取不到该令牌 直接返回请勿重复提交
public synchronized boolean findToken(String tokenKey) {
// 3.接口获取对应的令牌,如果能够获取该(从redis获取令牌)令牌(将当前令牌删除掉) 就直接执行该访问的业务逻辑
String tokenValue = (String) baseRedisService.getString(tokenKey);
if (StringUtils.isEmpty(tokenValue)) {
return false;
}
// 保证每个接口对应的token 只能访问一次,保证接口幂等性问题
baseRedisService.delKey(tokenValue);
return true;
}
}
4. 注解方式实现token的检查:
package com.hou.ext;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// 解决接口幂等性 支持网络延迟和表单重复提交
@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtApiIdempotent {
String type();
}
/**
* 功能说明:
* 功能作者:
* 创建日期:
*/
package com.hou.ext;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
*/
// 执行该请求的时候 需要生成令牌 转发到页面进行展示
@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtApiToken {
}
/**
*/
package com.hou.aop;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.itmayeidu.ext.ExtApiIdempotent;
import com.itmayeidu.ext.ExtApiToken;
import com.itmayeidu.utils.ConstantUtils;
import com.itmayeidu.utils.RedisToken;
/**
*/
@Aspect
@Component
public class ExtApiAopIdempotent {
@Autowired
private RedisToken redisToken;
// 1.使用AOP环绕通知拦截所有访问(controller)
@Pointcut("execution(public * com.hou.controller.*.*(..))")
public void rlAop() {
}
// 前置通知
@Before("rlAop()")
public void before(JoinPoint point) {
MethodSignature signature = (MethodSignature) point.getSignature();
ExtApiToken extApiToken = signature.getMethod().getDeclaredAnnotation(ExtApiToken.class);
if (extApiToken != null) {
// 可以放入到AOP代码 前置通知
getRequest().setAttribute("token", redisToken.getToken());
}
}
// 环绕通知
@Around("rlAop()")
public Object doBefore(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
// 2.判断方法上是否有加ExtApiIdempotent
MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
ExtApiIdempotent declaredAnnotation = methodSignature.getMethod().getDeclaredAnnotation(ExtApiIdempotent.class);
// 3.如何方法上有加上ExtApiIdempotent
if (declaredAnnotation != null) {
String type = declaredAnnotation.type();
// 如何使用Token 解决幂等性
// 步骤:
String token = null;
HttpServletRequest request = getRequest();
if (type.equals(ConstantUtils.EXTAPIHEAD)) {
token = request.getHeader("token");
} else {
token = request.getParameter("token");
}
if (StringUtils.isEmpty(token)) {
return "参数错误";
}
// 3.接口获取对应的令牌,如果能够获取该(从redis获取令牌)令牌(将当前令牌删除掉) 就直接执行该访问的业务逻辑
boolean isToken = redisToken.findToken(token);
// 4.接口获取对应的令牌,如果获取不到该令牌 直接返回请勿重复提交
if (!isToken) {
response("请勿重复提交!");
// 后面方法不在继续执行
return null;
}
}
// 放行
Object proceed = proceedingJoinPoint.proceed();
return proceed;
}
public HttpServletRequest getRequest() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
return request;
}
public void response(String msg) throws IOException {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletResponse response = attributes.getResponse();
response.setHeader("Content-type", "text/html;charset=UTF-8");
PrintWriter writer = response.getWriter();
try {
writer.println(msg);
} catch (Exception e) {
} finally {
writer.close();
}
}
}
5. 在control 中使用如下(非表单提交):
/**
*/
package com.hou.controller;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.hou.ext.ExtApiIdempotent;
import com.hou.utils.ConstantUtils;
import com.hou.utils.RedisToken;
import com.hou.entity.OrderEntity;
import com.hou.mapper.OrderMapper;
/**
*/
@RestController
public class OrderController {
@Autowired
private OrderMapper orderMapper;
@Autowired
private RedisToken redisToken;
// @Autowired
// private RedisTokenUtils redisTokenUtils;
//
// 从redis中获取Token
@RequestMapping("/redisToken")
public String RedisToken() {
return redisToken.getToken();
}
// @RequestMapping(value = "/addOrderExtApiIdempotent", produces =
// "application/json; charset=utf-8")
// @ExtApiIdempotent(type = ConstantUtils.EXTAPIHEAD)
// public String addOrderExtApiIdempotent(@RequestBody OrderEntity
// orderEntity, HttpServletRequest request) {
// // 如何使用Token 解决幂等性
// // 步骤:
// // 2.调用接口的时候,将该令牌放入的请求头中(获取请求头中的令牌)
// String token = request.getHeader("token");
// if (StringUtils.isEmpty(token)) {
// return "参数错误";
// }
// // 3.接口获取对应的令牌,如果能够获取该(从redis获取令牌)令牌(将当前令牌删除掉) 就直接执行该访问的业务逻辑
// boolean isToken = redisToken.findToken(token);
// // 4.接口获取对应的令牌,如果获取不到该令牌 直接返回请勿重复提交
// if (!isToken) {
// return "请勿重复提交!";
// }
// int result = orderMapper.addOrder(orderEntity);
// return result > 0 ? "添加成功" : "添加失败" + "";
// }
@RequestMapping(value = "/addOrderExtApiIdempotent", produces = "application/json; charset=utf-8")
@ExtApiIdempotent(type = ConstantUtils.EXTAPIHEAD)
public String addOrderExtApiIdempotent(@RequestBody OrderEntity orderEntity, HttpServletRequest request) {
int result = orderMapper.addOrder(orderEntity);
return result > 0 ? "添加成功" : "添加失败" + "";
}
}
6 在control 中使用如下(表单提交):
/**
*/
package com.hou.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.hou.ext.ExtApiIdempotent;
import com.hou.ext.ExtApiToken;
import com.hou.utils.ConstantUtils;
import com.hou.utils.RedisToken;
import com.hou.entity.OrderEntity;
import com.hou.mapper.OrderMapper;
/**
*/
@Controller
public class OrderPageController {
@Autowired
private OrderMapper orderMapper;
@Autowired
private RedisToken redisToken;
@RequestMapping("/indexPage")
@ExtApiToken
public String indexPage(HttpServletRequest req) {
return "indexPage";
}
@RequestMapping("/addOrderPage")
@ExtApiIdempotent(type = ConstantUtils.EXTAPIFROM)
public String addOrder(OrderEntity orderEntity) {
int addOrder = orderMapper.addOrder(orderEntity);
return addOrder > 0 ? "success" : "fail";
}
}
7.前端部分代码实现如下:
<form action="/addOrderPage" method="post">
<input type="hidden" name="token" value="${token}"> <span>订单名称</span><input
type="text" name="orderName"><br> <span>订单描述</span><input
type="text" name="orderDes"><br> <input type="submit">
</form>
标签:令牌,String,--,import,接口,token,org,服务器,com From: https://blog.51cto.com/u_15461374/5938164