接口-请求接入过滤器

导读:本篇文章讲解 接口-请求接入过滤器,文章出自:https://blog.csdn.net/weixin_43316702/article/details/119786151希望对大家有帮助,欢迎收藏,转发!站点地址:www.javazhiyin.com.com

>>强大,10k+点赞的 SpringBoot 后台管理系统竟然出了详细教程!

接口接入时会设置拦截,对一些非法请求或者异常请求进行拦截,现在我来分享一下关于接口接入时header过滤器的内容。

第一种:

@ApiOperation(value = "手动推送优惠券发放(券号)", notes = "")
@PostMapping(value = "/send/again", produces = MediaType.APPLICATION_JSON_VALUE)
public MqReceiveResponse sendCouponAgain(@RequestHeader(value = "userKey",required = false) String userKey, @RequestBody JSONObject jsonObject) {

    if (StringUtil.isBlankOrNull(userKey)){
        BusinessException.of("","userKey不能为空!");
    }

    if (!"zhangximing".equals(userKey)){
        BusinessException.of("","userKey不正确!");
    }

    String couponCodes = jsonObject.getString("couponCode");
    if (StringUtil.isBlankOrNull(couponCodes)){
        BusinessException.of("","couponCode不能为空");
    }
    List<String> couponList = Arrays.asList(couponCodes.split(","));

    logger.info("接收推送发放优惠券,接收报文:{}", couponCodes);

    MqReceiveResponse response = x2ToYzCouponService.sendCouponAgain(couponList);

    logger.info("响应推送发放优惠券,响应报文:{}", response.getMsg());

    return response;
}

请求过滤器的第一种写法:通过@RequestHeader这种方式比较不方便,接入时都得写一遍

第二种实现方式:设置拦截器,实现HandlerInterceptor

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Author: zhangximing
* Date: 2021/8/16 10:39
* FileName: AuthInterceptor
* Description: 交易前置拦截器
*/
@Component
@Slf4j
public class AuthInfoInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userInfo = request.getHeader("userKey");
        log.info(">>>>>>>拦截到api相关请求头<<<<<<<<" + userInfo);

        if (StringUtils.isEmpty(userInfo) || !"zhangximing".equals(userInfo)) {

            //直接搂下来,放到ThreadLocal中后续直接从中获取
            ThreadLocalUtils.set("userKey", userInfo);
            //抛出错误
            response.sendError(401,"userKey为空或不正确!");
            //false则到此为止
            return false;
//            BusinessException.of("","userKey为空或不正确!");
        }

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Exception
    {

        //移除userKey
        ThreadLocalUtils.remove("userKey");

        log.info("移除请求头中的userKey:" + ThreadLocalUtils.get("userKey"));
    }

}

工具类 ThreadLocalUtils

import java.util.*;

public class ThreadLocalUtils <T> {
    private static final ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal() {
        @Override
        protected Map<String, Object> initialValue() {
            return new HashMap<>(4);
        }
    };


    public static Map<String, Object> getThreadLocal(){
        return threadLocal.get();
    }

    public static <T> T get(String key) {
        Map map = (Map)threadLocal.get();
        return (T)map.get(key);
    }

    public static <T> T get(String key,T defaultValue) {
        Map map = (Map)threadLocal.get();
        return (T)map.get(key) == null ? defaultValue : (T)map.get(key);
    }

    public static void set(String key, Object value) {
        Map map = (Map)threadLocal.get();
        map.put(key, value);
    }

    public static void set(Map<String, Object> keyValueMap) {
        Map map = (Map)threadLocal.get();
        map.putAll(keyValueMap);
    }

    public static void remove() {
        threadLocal.remove();
    }

    public static <T> Map<String,T> fetchVarsByPrefix(String prefix) {
        Map<String,T> vars = new HashMap<>();
        if( prefix == null ){
            return vars;
        }
        Map map = (Map)threadLocal.get();
        Set<Map.Entry> set = map.entrySet();

        for( Map.Entry entry : set){
            Object key = entry.getKey();
            if( key instanceof String ){
                if( ((String) key).startsWith(prefix) ){
                    vars.put((String)key,(T)entry.getValue());
                }
            }
        }
        return vars;
    }

    public static <T> T remove(String key) {
        Map map = (Map)threadLocal.get();
        return (T)map.remove(key);
    }

    public static void clear(String prefix) {
        if( prefix == null ){
            return;
        }
        Map map = (Map)threadLocal.get();
        Set<Map.Entry> set = map.entrySet();
        List<String> removeKeys = new ArrayList<>();

        for( Map.Entry entry : set ){
            Object key = entry.getKey();
            if( key instanceof String ){
                if( ((String) key).startsWith(prefix) ){
                    removeKeys.add((String)key);
                }
            }
        }
        for( String key : removeKeys ){
            map.remove(key);
        }
    }
}

设置拦截器

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * 拦截设置 全部拦截校验
 * 一个*:只匹配字符,不匹配路径(/)
 * 两个**:匹配字符,和路径(/)
 * @author zhangximing
 * @since 2021/8/16
*/
  
@Configuration
public class WebConfig implements WebMvcConfigurer {
  
  
    @Autowired
    private AuthInfoInterceptor authInfoInterceptor;
  
  
    @Override
  
    public void addInterceptors(InterceptorRegistry registry) {
  
        registry.addInterceptor(authInfoInterceptor).addPathPatterns("/api/youzan/coupon/again/**");

    }
  
}