@Component
public class AppTokenInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String userId = request.getHeader("userId");
if (StringUtils.isNotBlank(userId) && !StringUtils.equals("0",userId)) {
ApUser apUser = new ApUser();
apUser.setId(Long.valueOf(userId));
AppThreadLocalUtil.setUser(apUser);
}
return super.preHandle(request, response, handler);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
AppThreadLocalUtil.clear();
super.postHandle(request, response, handler, modelAndView);
}
}
注入拦截器对象
ackage com.ligong.search.config;
import com.ligong.search.interceptor.AppTokenInterceptor;
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;
@Configuration
public class WmMvcConfig implements WebMvcConfigurer {
@Autowired
private AppTokenInterceptor appTokenInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(appTokenInterceptor).addPathPatterns("/api/**");
}
}
|