赞
踩
OncePerRequestFilter接口就是每次发起请求,确保只会执行一次。
public class MyRequestContext { public static final String USER_ID = "user_id"; public static final String ACCESS_TOKEN = "accessToken"; public static final String PROTOCOL_SCHEME = "Protocol-Scheme"; private static final ThreadLocal<Map<String, Object>> USER_LOCAL = new InheritableThreadLocal<Map<String, Object>>(); private MyRequestContext() { } public static Object get(String key) { return ((Map)USER_LOCAL.get()).get(key); } public static void put(String key, Object value) { ((Map)USER_LOCAL.get()).put(key, value); } public static void remove() { USER_LOCAL.remove(); } public static Map<String, Object> getAll() { return (Map)USER_LOCAL.get(); } }
public class RequestLinkContextFilter extends OncePerRequestFilter { private static final Logger log = LoggerFactory.getLogger(RequestLinkContextFilter.class); public RequestLinkContextFilter() { } protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { String userId = request.getHeader("user_id"); if (StringUtils.isNotBlank(userId)) { MyRequestContext.put("user_id", Long.parseLong(userId)); } String accessToken = request.getHeader("accessToken"); if (StringUtils.isNotBlank(accessToken)) { MyRequestContext.put("accessToken", accessToken); } String protocolScheme = request.getHeader("Protocol-Scheme"); if (StringUtils.isNotBlank(protocolScheme)) { MyRequestContext.put("Protocol-Scheme", protocolScheme); } String originFrom = request.getHeader("origin-from"); if (StringUtils.isNotBlank(originFrom)) { MyRequestContext.put("origin-from", originFrom); } try { chain.doFilter(request, response); } finally { MyRequestContext.remove(); } } }
public class MyFeignInterceptor implements RequestInterceptor { public MyFeignInterceptor() { } public void apply(RequestTemplate template) { Map<String, Object> allContext = MyRequestContext.getAll(); if (!MapUtils.isEmpty(allContext)) { Iterator var3 = allContext.entrySet().iterator(); while(var3.hasNext()) { Entry<String, Object> entry = (Entry)var3.next(); if (entry.getValue() instanceof String) { template.header((String)entry.getKey(), new String[]{entry.getValue().toString()}); } else { template.header((String)entry.getKey(), new String[]{JSON.toJSONString(entry.getValue())}); } } } } }
public class MyHttpRequestInterceptor implements ClientHttpRequestInterceptor { public MyHttpRequestInterceptor() { } public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { HttpHeaders headers = request.getHeaders(); Map<String, Object> allContext = MyRequestContext.getAll(); if (MapUtils.isEmpty(allContext)) { return execution.execute(request, body); } else { Iterator var6 = allContext.entrySet().iterator(); while(var6.hasNext()) { Entry<String, Object> entry = (Entry)var6.next(); if (!headers.containsKey(entry.getKey())) { if (entry.getValue() instanceof String) { headers.add((String)entry.getKey(), entry.getValue().toString()); } else { headers.add((String)entry.getKey(), JSON.toJSONString(entry.getValue())); } } } return execution.execute(request, body); } } }
HandlerInterceptor是最常规的,其拦截的http请求是来自于客户端浏览器之类的,是最常见的http请求拦截器
public class LoginFilter extends HandlerInterceptorAdapter { private final Logger logger = LoggerFactory.getLogger(LoginFilter.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { logger.info("request请求地址path[{}] uri[{}]", request.getServletPath(),request.getRequestURI()); //request.getHeader(String) 从请求头中获取数据 //从请求头中获取用户token Long userId= getUserId(request.getHeader("H-User-Token")); if (userId != null && checkAuth(userId,request.getRequestURI())){ return true; } //这里的异常是我自定义的异常,系统抛出异常后框架捕获异常然后转为统一的格式返回给前端, 其实这里也可以返回false throw new FastRuntimeException(20001,"No access"); } private Long getUserId(String userToken){ Long userId = null; return userId; } private boolean checkAuth(Long userId,String requestURI){ return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {} @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {} }
ClientHttpRequestInterceptor是对RestTemplate的请求进行拦截的,在项目中直接使用restTemplate.getForObject的时候,会对这种请求进行拦截,经常被称为:RestTempalte拦截器或者Ribbon拦截器;
RequestInterceptor常被称为是Feign拦截器,由于Feign调用底层实际上还是http调用,因此也是一个http拦截器,在项目中使用Feign调用的时候,可以使用此拦截器
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。