spring boot中interceptor攔截器未生效的解決
interceptor攔截器未生效
搭建項(xiàng)目時(shí)發(fā)現(xiàn)攔截器未生效
開始用的spring boot版本為1.5.6
代碼如下:
@Configuration public class WebConfig extends WebMvcConfigurerAdapter{ @Autowired private TimeInterceptor timeInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(this.timeInterceptor); super.addInterceptors(registry); } }
@Component public class RequestParamInfoIntorceptor extends HandlerInterceptorAdapter { private Logger logger = LoggerFactory.getLogger(RequestParamInfoIntorceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { try { if (handler instanceof HandlerMethod) { HandlerMethod handlerMethod = (HandlerMethod) handler; String beanName = handlerMethod.getBean().getClass().toString();//類 String methodName = handlerMethod.getMethod().getName();//方法名稱 if(methodName.equals("error") || methodName.equals("success")) { return super.preHandle(request, response, handler); } String uri = request.getRequestURI();//請(qǐng)求路徑 String remoteAddr = getIpAddr(request);//ip String method = request.getMethod(); //請(qǐng)求方式 Map<String,String[]> pramMap = request.getParameterMap(); StringBuffer sbf = new StringBuffer(); int count = 0; String forCunt = ""; for(Map.Entry<String, String[]> entry:pramMap.entrySet()){ forCunt = "[" + count + "]" + " : " ; sbf.append( "paramName" + forCunt + entry.getKey() + " - "+ "paramValue" + forCunt + request.getParameter(entry.getKey()) + "\n"); count ++; } logger.info(" { beanName : " + beanName + " | " + "methodName : " + methodName + " | " + "uri : " + uri + " | " + "remoteAddr : " + remoteAddr + " | " + "requestMethod : " + method + "\n" + "param : " + sbf + "}"); } } catch (Exception e) { //出錯(cuò) logger.error(e.toString()); } return super.preHandle(request, response, handler); } //獲取客戶端IP private String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } }
開始以為是版本問(wèn)題,后升級(jí)為2.1.1,WebConfig改為實(shí)現(xiàn)WebMvcConfigurer,代碼如下
@Configuration @Component public class WebConfig implements WebMvcConfigurer{ @Autowired private RequestParamInfoIntorceptor requestParamInfoIntorceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(this.requestParamInfoIntorceptor).addPathPatterns("/**"); } }
驗(yàn)證后還是不行,繼續(xù)排查后發(fā)現(xiàn),在添加版本控制時(shí),有配置類繼承了WebMvcConfigurationSupport,查詢WebMvcConfigurationSupport源碼發(fā)現(xiàn)其中有攔截器注冊(cè)方法addInterceptors(InterceptorRegistry registry),所以在版本控制配置類中重寫此方法添加攔截器,攔截器生效,問(wèn)題解決。
解決方案
代碼如下:
@Configuration public class ApiConfig extends WebMvcConfigurationSupport { @Autowired private RequestParamInfoIntorceptor requestParamInfoIntorceptor; @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(this.requestParamInfoIntorceptor).addPathPatterns("/**"); super.addInterceptors(registry); } }
HandlerInterceptor實(shí)現(xiàn)登錄失效攔截等
首先寫一個(gè)實(shí)現(xiàn)HandlerInterceptor的類
代碼如下:
public class SessionInterceptor implements HandlerInterceptor { @Autowired RedisTemplate<String, String> redisTemplate; //private static String LOGIN_CODE = "/user/no_loginPage?Landingcode=" + UserResourcesHelper.LANDINGCODE_106;// 登錄地址及code信息 //private static String LOGIN_CODE = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd11f95277f85e24b&redirect_uri=&response_type=code&scope=snsapi_userinfo&state=1234#wechat_redirect"; protected List<String> patterns = new ArrayList<String>(Arrays.asList(".*?/.*/no_.*?", "/", "/error")); public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 一些不需要過(guò)濾的方法 String url = request.getRequestURI(); if (isInclude(url) == true) return true; // 權(quán)限校驗(yàn) Cookie cookie = getCookieByName(request, UserResourcesHelper.COOKIE_TOKEN_NAME); String user = null; if (cookie != null && !cookie.getValue().equals("")) { user = redisTemplate.opsForValue().get(RedisKeyConstant.USER_WEB_TOKEN + cookie.getValue()); } if (cookie == null || user == null) {// 判斷用戶是否經(jīng)過(guò)了授權(quán) // 判斷是否是AJAX訪問(wèn) if (request.getHeader("x-requested-with") != null && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) { response.setHeader("sessionstatus", "timeout"); response.setStatus(403); return false; } else { response.sendRedirect(request.getContextPath()+"/home/no_index_toLoginSkip"); //response.sendRedirect(request.getContextPath() +UserResourcesHelper.LOGIN_URL); // 非AJAX訪問(wèn),頁(yè)面跳轉(zhuǎn) //response.sendRedirect(request.getContextPath() +"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxd11f95277f85e24b&redirect_uri="+URLEncoder.encode("http://m.hobay.cn/user/no_loginPage", "utf-8")+"&response_type=code&scope=snsapi_base&state=123#wechat_redirect"); // 非AJAX訪問(wèn),頁(yè)面跳轉(zhuǎn) return false; } } 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 { } private boolean isInclude(String url) { for (String pattern : patterns) { if (Pattern.matches(pattern, url)) { return true; } } return false; } /** * 根據(jù)名字獲取cookie * * @param request * @param name * cookie名字 * @return */ private static Cookie getCookieByName(HttpServletRequest request, String name) { Map<String, Cookie> cookieMap = ReadCookieMap(request); if (cookieMap.containsKey(name)) { Cookie cookie = (Cookie) cookieMap.get(name); return cookie; } else { return null; } } /** * 將cookie封裝到Map里面 * * @param request * @return */ private static Map<String, Cookie> ReadCookieMap(HttpServletRequest request) { Map<String, Cookie> cookieMap = new HashMap<String, Cookie>(); Cookie[] cookies = request.getCookies(); if (null != cookies) { for (Cookie cookie : cookies) { cookieMap.put(cookie.getName(), cookie); } } return cookieMap; }
然后把這個(gè)攔截器注冊(cè)到spring中
代碼如下:
@EnableWebMvc @Configuration public class WebConfig extends WebMvcConfigurerAdapter{ @Bean SessionInterceptor sessioninterceptor() { return new SessionInterceptor(); } /** * 配置攔截器 * @author yuqingquan * @param registry */ public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(sessioninterceptor()); }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
java 算法之希爾排序詳解及實(shí)現(xiàn)代碼
這篇文章主要介紹了java 算法之希爾排序詳解及實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2017-03-03解決rocketmq-spring-boot-starter導(dǎo)致的多消費(fèi)者實(shí)例重復(fù)消費(fèi)問(wèn)題
這篇文章主要介紹了解決rocketmq-spring-boot-starter導(dǎo)致的多消費(fèi)者實(shí)例重復(fù)消費(fèi)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06解決mybatis分頁(yè)插件PageHelper導(dǎo)致自定義攔截器失效
這篇文章主要為大家介紹了解決mybatis分頁(yè)插件PageHelper導(dǎo)致自定義攔截器失效方案示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08Springboot升級(jí)到2.7.2結(jié)合nacos遇到的坑及解決
這篇文章主要介紹了Springboot升級(jí)到2.7.2結(jié)合nacos遇到的坑及解決,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-06-06Mybatis的parameterType造成線程阻塞問(wèn)題分析
這篇文章主要詳細(xì)分析了Mybatis的parameterType造成線程阻塞問(wèn)題,文中有詳細(xì)的解決方法,及相關(guān)的代碼示例,具有一定的參考價(jià)值,感興趣的朋友可以借鑒閱讀2023-06-06java如何實(shí)現(xiàn)項(xiàng)目啟動(dòng)時(shí)執(zhí)行指定方法
這篇文章主要為大家詳細(xì)介紹了java項(xiàng)目如何啟動(dòng)時(shí)執(zhí)行指定方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-07-07