文件名称:java拦截器
文件大小:3KB
文件格式:JAVA
更新时间:2021-10-17 03:20:47
java
拦截器类 需要两个配合使用这里只有一个 @Configuration public class ServletContextConfig extends WebMvcConfigurerAdapter { public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); registry.addResourceHandler("/templates/**").addResourceLocations("classpath:/templates/"); super.addResourceHandlers(registry); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new HandlerMyInterceptorAdapter()).addPathPatterns("/**") .excludePathPatterns("/") // .excludePathPatterns("/expressions/getExpressionsList") .excludePathPatterns("/loginInfo/getCordByIsPhone") .excludePathPatterns("/loginInfo/login11") //token失效跳轉 .excludePathPatterns("/loginInfo/insertLoginInfo") //注册 .excludePathPatterns("/loginInfo/login") //登录 .excludePathPatterns("/upload") //上传文件 .excludePathPatterns("/uploadListen") //上传文件 .excludePathPatterns("/admin/user/goLogin") //后台跳转登录 .excludePathPatterns("/admin/user/login") //后台登录 .excludePathPatterns("/loginInfo/getLoginInfo") //忘记密码 .excludePathPatterns("/loginInfo/getCord") //短信验证码 .excludePathPatterns("/loginInfo/getIsLoginInfo") //判断验证码&&登录 .excludePathPatterns("/loginInfo/getIsLoginInfo1") //判断验证码 .excludePathPatterns("/loginInfo/setPassWord") //设置密码 ; } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } } @Component public class HandlerMyInterceptorAdapter implements HandlerInterceptor { @Autowired private HeartbeatServiceImpl heartbeatService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException { String url = request.getRequestURI(); if (url.contains("admin")) { User user = (User) request.getSession().getAttribute("user"); try { if (user.equals(null)) { response.sendRedirect(serverConfig.SERVER + "admin/user/goLogin"); return false; } else { return true; } }catch (Exception e){ response.sendRedirect(serverConfig.SERVER + "admin/user/goLogin"); return false; } }else { String token = request.getHeader("token"); if (token != null) { Jedis jedis = new Jedis(com.sevenSteps.util.RedisConfig.HOST, RedisConfig.PORT); String s = jedis.get(token); if(token.equals(s)) { heartbeatService = SpringUtil.getBean(HeartbeatServiceImpl.class); return heartbeatService.setOutDate(token); }else { response.sendRedirect(serverConfig.SERVER + "loginInfo/login11"); return true; } }else { response.sendRedirect(serverConfig.SERVER + "loginInfo/login11"); return true; } } } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { } }