自定义拦截器
自定义一个类 实现 HandlerInterceptor 接口 并重写里面的方法 preHandle、postHandle、afterCompletion
preHandle:在执行具体的Controller方法之前调用
postHandle:controller执行完毕之后被调用
afterCompletion:方法需要在当前对应的 Interceptor 类的 preHandle 方法返回值为 true 时才会执行。 顾名思义,该方法将在整个请求结束之后,也就是在 DispatcherServlet 渲染了对应的视图之后执行。此方法主要用来进行资源清理。
package com.baymax.vpp.cop.pay.filter;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baymax.core.tool.utils.Func;
import com.baymax.vpp.cop.common.enums.core.EUseOrg;
import com.baymax.vpp.cop.common.enums.device.ERetStat;
import com.baymax.vpp.cop.common.utils.HMacMD5Util;
import com.baymax.vpp.cop.common.utils.RedisUtil;
import com.baymax.vpp.cop.pay.constant.XiaoJuConstant;
import com.baymax.vpp.cop.pay.utils.RequestUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@Slf4j
public class MyInterceptor implements HandlerInterceptor {
@Autowired
private RedisUtil redisUtil;
private static final String AUTHORIZATION_HEADER = "Authorization";
private static final String OPERATOR_ID = "OperatorID";
private static final String SIG = "Sig";
private static final String TIME_STAMP = "TimeStamp";
private static final String SEQ = "Seq";
private static final String DATA = "Data";
@Override
public boolean preHandle(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler) throws Exception {
log.info("拦截器拦截请求,请求路径:{}", request.getServletPath());
String accessToken = request.getHeader(AUTHORIZATION_HEADER);
String path = request.getServletPath();
String requestBody = RequestUtil.getRequestBody(request);
JSONObject requestBodyJson = JSON.parseObject(requestBody);
if (Func.isEmpty(requestBodyJson)) {
setErrorResponse(response, ERetStat.paramError, "参数错误");
return false;
}
String operatorID = Func.toStr(requestBodyJson.getString(OPERATOR_ID));
String sig = Func.toStr(requestBodyJson.getString(SIG));
String timeStamp = Func.toStr(requestBodyJson.getString(TIME_STAMP));
String seq = Func.toStr(requestBodyJson.getString(SEQ));
String data = Func.toStr(requestBodyJson.getString(DATA));
log.info("operatorID:{}, sig:{}, timeStamp:{}, seq:{}, data:{}", operatorID, sig, timeStamp, seq, data);
if (!verifySignature(operatorID, data, timeStamp, seq, sig)) { // 签名需要生成
log.info("签名错误");
setErrorResponse(response, ERetStat.signError, "签名错误");
return false;
}
boolean isAccessTokenRequest = path.contains("query_token");
if (isAccessTokenRequest) {
// 处理AccessToken请求
return true;
}
if (Func.isEmpty(accessToken)) {
setErrorResponse(response, ERetStat.tokenError, "Token错误");
return false;
} else {
// 验证Token
// TODO
String tokenRel = "Bearer " + redisUtil.getString( XiaoJuConstant.TOKEN_XIAOJU_ERP + EUseOrg.XIAOJU.getValue() );
if (!tokenRel.equals(accessToken)) {
setErrorResponse(response, ERetStat.tokenError, "Token错误");
return false;
}
return true;
}
}
@Override
public void postHandle(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, ModelAndView modelAndView) throws Exception {
HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
}
@Override
public void afterCompletion(@NotNull HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull Object handler, Exception ex) throws Exception {
HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
}
}
开始注册拦截器
1、在启动类main方法里面实现 接口 WebMvcConfigurer 重写方法 addInterceptors
@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**"); }
2、方法
自定义一个配置类 通过注解:@Configuration 和 @Bean 实现接口 WebMvcConfigurer
package com.baymax.vpp.cop.pay.config;
import com.baymax.vpp.cop.pay.filter.MyInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
//注册拦截器
@Bean
public MyInterceptor myInterceptor() {
return new MyInterceptor();
}
//添加拦截器到springmvc 拦截器链
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(myInterceptor()).addPathPatterns("/client/openApi/xiaojuErp/**");
}
}