目录
1.编写拦截器实现类,实现接口 HandlerInterceptor,
重写里面需要的三个比较常用的方法,实现自己的业务逻辑代码
(就是自己拦截器拦截时做什么处理)
AccessInterceptor
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com.hcycom.mc.web.access;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.hcycom.mc.web.dto.SysUserDTO;
import com.hcycom.mc.web.redis.RedisClusterConfig;
import com.hcycom.mc.web.redis.RedisPoolFactory;
import com.hcycom.mc.web.redis.RedisService;
import com.hcycom.mc.web.redis.UserKey;
import com.hcycom.mc.web.utils.ExpiryMap;
import com.hcycom.mc.web.utils.HttpRequestUtil;
import com.hcycom.mc.web.utils.MemoryUtil;
import com.hcycom.mc.web.utils.ResultVOUtil;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import jodd.net.URLCoder;
import jodd.util.StringUtil;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.elasticsearch.rest.RestRequest.Method;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
@Component
@Configuration
public class AccessInterceptor implements HandlerInterceptor {
private static final Logger log = LoggerFactory.getLogger(AccessInterceptor.class);
static final Logger logger = LoggerFactory.getLogger(AccessInterceptor.class);
static final List<String> filterMethod = new ArrayList(100);
static final List<String> filterUrl = new ArrayList(100);
static final List<String> policyUrl = new ArrayList(100);
public static ExpiryMap<String, String> onlineUserMap = new ExpiryMap(1800000L);
@Value("${ssoUrl}")
private String ssoUrl;
private RedisService redisService;
private RedisPoolFactory redisPoolFactory;
private RedisClusterConfig redisClusterConfig;
static CloseableHttpClient httpClient;
public AccessInterceptor() {
init();
}
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("method:" + request.getMethod());
if (request.getMethod().equals(Method.OPTIONS.toString())) {
this.render(response, "ok");
return true;
} else {
SysUserDTO u = null;
String ip = "";
String token = "";
if (!(handler instanceof HandlerMethod)) {
return true;
} else {
HandlerMethod handlerMethod = (HandlerMethod)handler;
java.lang.reflect.Method method = handlerMethod.getMethod();
String className = method.getDeclaringClass().getSimpleName();
String name = method.getDeclaringClass().getName();
if (!name.startsWith("com.hcycom")) {
return true;
} else {
Object bean = handlerMethod.getBean();
Object self = AopTargetUtils.getTarget(bean);
String uuid = UUID.randomUUID().toString();
request.setAttribute("__UUID__", uuid);
Class c = self.getClass();
String msg = MemoryUtil.getMemoryInfo(this, "AccessInterceptor");
log.debug(msg);
int status = response.getStatus();
if (status == 404) {
return true;
} else if (handler instanceof HandlerMethod) {
HandlerMethod hm = (HandlerMethod)handler;
String methodName = hm.getMethod().getName();
String url = request.getRequestURL().toString();
log.info(url);
log.info("methodName=" + methodName);
String t;
try {
Iterator var20 = policyUrl.iterator();
while(var20.hasNext()) {
String s = (String)var20.next();
if (url.contains(s)) {
t = request.getParameter("guest");
if (null != t && !"".equals(t)) {
logger.info(url, s);
return true;
}
}
}
} catch (Exception var39) {
log.error("", var39);
}
JedisPool jedisPool = null;
JedisCluster jedisCluster = null;
try {
ip = HttpRequestUtil.getIpAddr(request);
token = "" + this.getToken(request);
this.redisService = (RedisService)SpringBeanUtils.getBean("redisService");
this.redisClusterConfig = (RedisClusterConfig)SpringBeanUtils.getBean("redisClusterConfig");
this.redisPoolFactory = (RedisPoolFactory)SpringBeanUtils.getBean("redisPoolFactory");
try {
jedisCluster = this.redisClusterConfig.init();
jedisPool = this.redisPoolFactory.JedisPoolFactory();
} catch (Exception var36) {
}
u = (SysUserDTO)this.redisService.get(jedisPool, jedisCluster, UserKey.token, token, SysUserDTO.class);
request.setAttribute("_USER", u);
} catch (Exception var37) {
logger.error("取token失败", var37);
} finally {
try {
if (jedisPool != null) {
jedisPool.close();
}
if (jedisCluster != null) {
jedisCluster.close();
}
} catch (Exception var34) {
}
}
String s;
try {
if (u == null) {
t = URLCoder.encodeQueryParam(token);
logger.info("根据token取sso的用户" + t);
s = this.getUserInfoByToken(t);
if (StringUtil.isBlank(s)) {
HttpRequest req = HttpRequest.get(this.ssoUrl + "/user/getUserByToken?token=" + t);
HttpResponse res = req.send();
res.charset("utf-8");
s = res.bodyText();
log.info("连接sso取用户");
}
SysUserDTO user = (SysUserDTO)JSON.parseObject(s, SysUserDTO.class);
log.info("sso用户信息{}", user);
if (user != null) {
logger.info(user.getId());
u = user;
request.setAttribute("_USER", user);
}
}
} catch (Exception var35) {
logger.error("取sso用户失败", var35);
}
Iterator var42 = filterMethod.iterator();
do {
if (!var42.hasNext()) {
if (c.isAnnotationPresent(NoToken.class)) {
return true;
}
if (c.isAnnotationPresent(Controller.class)) {
return true;
}
if (method.getAnnotation(NoToken.class) != null) {
return true;
}
if (filterMethod.contains(methodName)) {
return true;
}
var42 = filterUrl.iterator();
do {
if (!var42.hasNext()) {
if (u != null && null != u.getId() && !"".equals(u.getId()) && null != u.getLoginName() && !"".equals(u.getLoginName())) {
request.setAttribute("_USER", u);
ExpiryMap<String, String> map = onlineUserMap;
logger.info("当前登录用户IP:" + ip + " token:" + token + " userId:" + u.getId());
map.put(u.getId(), token);
return true;
}
this.render(response, "您的用户已失效, 请重新登录!");
return false;
}
s = (String)var42.next();
} while(!url.contains(s));
logger.info("xxxxxxxxxxxxxxxxxxxxxxxx=" + url + s);
return true;
}
s = (String)var42.next();
} while(!url.contains(s));
return true;
} else {
return true;
}
}
}
}
}
public static void init() {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(60000L, TimeUnit.MILLISECONDS);
connectionManager.setMaxTotal(1000);
connectionManager.setDefaultMaxPerRoute(50);
(new IdleConnectionEvictor(connectionManager)).start();
httpClient = HttpClients.custom().setConnectionManager(connectionManager).disableAutomaticRetries().build();
}
String getUserInfoByToken(String token) {
CloseableHttpResponse response = null;
String var6;
try {
HttpGet httpGet = new HttpGet(this.ssoUrl + "/user/getUserByToken?token=" + token);
Builder builder = RequestConfig.custom();
builder.setSocketTimeout(5000).setConnectTimeout(2000).setConnectionRequestTimeout(3000);
httpGet.setConfig(builder.build());
response = httpClient.execute(httpGet);
if (200 != response.getStatusLine().getStatusCode()) {
return "";
}
String strResult = EntityUtils.toString(response.getEntity());
var6 = strResult;
} catch (Exception var17) {
var17.printStackTrace();
log.error("取token异常", var17);
return "";
} finally {
if (null != response) {
try {
EntityUtils.consume(response.getEntity());
} catch (Exception var16) {
}
}
}
return var6;
}
private void render(HttpServletResponse response, String msg) throws Exception {
response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
String str = JSON.toJSONString(ResultVOUtil.error(1, msg));
out.print(str);
out.flush();
out.close();
}
private String getToken(HttpServletRequest request) {
String token = request.getParameter("token");
if (StringUtils.isEmpty(token)) {
token = request.getHeader("mc-access-token");
}
if (StringUtils.isEmpty(token)) {
token = request.getHeader("sso-access-token");
}
if (StringUtils.isEmpty(token)) {
token = request.getHeader("Authorization");
}
if (StringUtils.isEmpty(token)) {
token = request.getHeader("token");
}
if (StringUtils.isEmpty(token)) {
Cookie[] c = request.getCookies();
if (c != null) {
Cookie[] var4 = c;
int var5 = c.length;
for(int var6 = 0; var6 < var5; ++var6) {
Cookie co = var4[var6];
if ("token".equals(co.getName())) {
token = co.getValue();
break;
}
if ("sso-token".equals(co.getName())) {
token = co.getValue();
break;
}
if ("Authorization".equals(co.getName())) {
token = co.getValue();
break;
}
}
}
}
return token;
}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {
String msg = MemoryUtil.getMemoryInfo(this, "========执行后的内存情况");
log.debug(msg);
}
static {
filterMethod.add("auth");
filterMethod.add("jsonpGetToken");
filterMethod.add("login");
filterMethod.add("logout");
filterMethod.add("getByToken");
filterMethod.add("authenticationCode");
filterMethod.add("get5GCProvinceConnect");
filterMethod.add("get5GCThreeLayersTopo");
filterMethod.add("get5GCNodeAMFAlarm");
filterMethod.add("get5GCNodeSMFAlarm");
filterMethod.add("get5GCNodeUDMAlarm");
filterMethod.add("get5GCNodePCFAlarm");
filterMethod.add("get5GCNodeNSSFAlarm");
filterMethod.add("get5GCNodeUPFAlarm");
filterMethod.add("get5GCLinkN4Alarm");
filterMethod.add("get5GCLinkN7Alarm");
filterMethod.add("get5GCLinkN8Alarm");
filterMethod.add("get5GCLinkN10Alarm");
filterMethod.add("get5GCLinkN11Alarm");
filterMethod.add("get5GCLinkN22Alarm");
filterMethod.add("get5GCProvinceConnectLink");
filterMethod.add("get5GCProvinceConnectCount");
filterMethod.add("get5GCProvinceConnectLinkCount");
filterMethod.add("get5GCWorkOrderFault");
filterMethod.add("get5GCAlarmByOrderId");
filterMethod.add("get5GCWorkOrderFaultCount");
filterMethod.add("queryNeName");
filterMethod.add("queryNeTree");
filterMethod.add("findAllCity");
filterMethod.add("get5GYFaultCountByProvince");
filterMethod.add("getSheetCountNearHours");
filterMethod.add("get5GCAlarmCountNearHours");
filterMethod.add("get5GYSheetCountNearHours");
filterMethod.add("get5GYAlarmCountNearHours");
filterMethod.add("getUserCount");
filterMethod.add("queryDCNameByProvince");
filterMethod.add("leftNearHours");
filterMethod.add("topNearHours");
filterMethod.add("getWorkOrderByType");
filterMethod.add("getWorkOrderByLevel");
filterMethod.add("getWordOrderByYW");
filterMethod.add("getOriginalAlarmCount");
filterMethod.add("getOriginalAlarmCountOld");
filterMethod.add("getOriginalAlarmHourCount");
filterMethod.add("getCollect");
filterMethod.add("get5GCAlarmAnalysisCount");
filterMethod.add("get5GCAlarmListByOrderId");
filterMethod.add("getFaultOrder");
filterMethod.add("getChildrenAlarmProvinceConnect");
filterMethod.add("getChildrenAlarmProvinceConnectCount");
filterMethod.add("getChildrenAlarmProvinceConnectLink");
filterMethod.add("getNetcoolClearAlarmCount");
filterMethod.add("get5GcIByFnAndPro");
filterMethod.add("get5GcIByFnProAndNa");
filterMethod.add("getCount");
filterMethod.add("getList");
filterMethod.add("getListByText");
filterMethod.add("getViewList");
filterMethod.add("getAlarmListByVendor");
filterMethod.add("getEORAlarmCount");
filterMethod.add("getCRAlarmCount");
filterMethod.add("getSRAlarmCount");
filterMethod.add("getDCAlarm");
filterMethod.add("getSendOrderCount");
filterMethod.add("getNetcool5GAlarmCount");
filterMethod.add("searchWarningCount");
filterMethod.add("getSituation");
filterMethod.add("getAlarmBySpecialtyId");
filterMethod.add("queryByUser");
filterMethod.add("getAlarmLevelCount");
filterMethod.add("queryAlarmById");
filterMethod.add("getAlarmDetailTempplete");
filterMethod.add("getImpactTree");
filterMethod.add("getAlarmTrail");
filterUrl.add("/mc/glPonUsers/findAll");
policyUrl.add("/policy/policy/searchExeList");
policyUrl.add("/policy/policy/exePolicy");
policyUrl.add("/policy/policy/sendPolicy");
policyUrl.add("/rule/ruleAlarmCustomize/queryByUser");
policyUrl.add("/alarm/getAlarmLevelCount");
}
}
2.编写拦截器配置文件类并继承 WebMvcConfigurer类,并重写其中的方法 addInterceptors并且在主类上加上注解 @Configuration
WebConfig
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com.hcycom.mc.web.config;
import com.hcycom.mc.web.access.AccessInterceptor;
import java.beans.ConstructorProperties;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.validation.MessageCodesResolver;
import org.springframework.validation.Validator;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig extends WebMvcConfigurationSupport implements WebMvcConfigurer {
@Autowired
AccessInterceptor accessInterceptor;
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(new String[]{"druid/index.html"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/"});
registry.addResourceHandler(new String[]{"swagger-ui.html"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/"});
registry.addResourceHandler(new String[]{"/webjars/**"}).addResourceLocations(new String[]{"classpath:/META-INF/resources/webjars/"});
registry.addResourceHandler(new String[]{"/static/**"}).addResourceLocations(new String[]{"classpath:/static/", "classpath:/image/"});
}
public void configurePathMatch(PathMatchConfigurer configurer) {
}
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
}
public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
}
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
}
public void addFormatters(FormatterRegistry registry) {
}
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(this.accessInterceptor).addPathPatterns(new String[]{"/**"}).excludePathPatterns(new String[]{"/login", "/swagger-**/**"});
super.addInterceptors(registry);
}
public void addCorsMappings(CorsRegistry registry) {
}
public void addViewControllers(ViewControllerRegistry registry) {
}
public void configureViewResolvers(ViewResolverRegistry registry) {
}
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
}
public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> handlers) {
}
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
}
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
}
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
}
public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
}
public Validator getValidator() {
return null;
}
public MessageCodesResolver getMessageCodesResolver() {
return null;
}
@ConstructorProperties({"accessInterceptor"})
public WebConfig(final AccessInterceptor accessInterceptor) {
this.accessInterceptor = accessInterceptor;
}
}