spring 将拦截器数据传输到controller

spring 将拦截器数据传输到controller

今天在写一个接口项目的时候,我们提供给别人的接口数据,我们所有的接口都是要从header中获取一个凭证,

这个凭证需要从数据库中查询一些数据,然后给接下来的controller中使用,解决方案如下:

1、AuthInterceptor.java 拦截器

@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {

public final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);



@Value(value = "${spring.profiles.active}")
String springProfilesActive;

@Autowired
PartnerService partnerService;

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String partnerNo = request.getHeader("partnerNo");
response.setCharacterEncoding("UTF-8");
if(StringUtil.isNil(partnerNo)){
ResponseHelper.write(response, JsonUtil.beanToJson(WebUtil.tokenError("partnerNo不能为空")));
return false;
}else{
PartnerDto partnerDto=partnerService.getPartner(partnerNo);
if(partnerDto==null){
ResponseHelper.write(response, JsonUtil.beanToJson(WebUtil.tokenError("合作伙伴信息不存在")));
}
PartnerThreadLocal.set(partnerDto);

}
request.setAttribute("startTime",System.currentTimeMillis());
return true;
}

private boolean validUrl(HttpServletRequest request) {
logger.info("================>>>>springProfilesActive={}",springProfilesActive);
if (StringUtil.isBlank(springProfilesActive) || !"dev".equals(springProfilesActive)){
return true;
}
String reqUrl = request.getRequestURI();
for (int i = 0; i < WebConfig.globalFunction.length; i++) {
String url = WebConfig.globalFunction[i];
if (reqUrl.contains(url)){
return false;
}
}
return true;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
super.postHandle(request, response, handler, modelAndView);
//long endTime = System.currentTimeMillis();
//long startTime = (Long)request.getAttribute("startTime");
//long executeTime = endTime - startTime;
//logger.debug("[" + handler + "] \n 执行耗时 : " + executeTime + "ms");
}

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//本次请求完成,清空合作伙伴信息
PartnerThreadLocal.set(null);
super.afterCompletion(request, response, handler, ex);
}
}



2、PartnerThreadLocal.java 

package com.kaishi.kscs.api.auth.bean;

import com.kaishi.kscs.admin.dto.PartnerDto;

/**
* 合作伙伴数据缓存(仅当次请求有效)
* @author dengjihai
* @create 2018-06-06
**/
public class PartnerThreadLocal {

private PartnerThreadLocal(){

}

private static final ThreadLocal<PartnerDto> partnerDtoThreadLocal = new ThreadLocal<>();


public static void set(PartnerDto partnerDto){
partnerDtoThreadLocal.set(partnerDto);
}

public static PartnerDto get(){
return partnerDtoThreadLocal.get();
}


}
  • 发表于 2018-06-06 14:40
  • 阅读 ( 1047 )
  • 分类:Java

0 条评论

请先 登录 后评论
不写代码的码农
威猛的小站长

107 篇文章

作家榜 »

  1. 威猛的小站长 107 文章
  2. Jonny 65 文章
  3. 江南烟雨 33 文章
  4. - Nightmare 33 文章
  5. doublechina 31 文章
  6. HJ社区-肖峰 29 文章
  7. 伪摄影 20 文章
  8. Alan 14 文章