SpringBoot 2.x 自定義攔截器並解決靜態資源訪問被攔截問題


 

自定義攔截器

/** * UserSecurityInterceptor * Created with IntelliJ IDEA. * Author: yangyongkang * Date: 2018/8/22 * Time: 14:20 */ @Component public class UserSecurityInterceptor implements HandlerInterceptor { @Autowired private RedisTemplate<String, Serializable> redisCacheTemplate; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { UserModel info = (UserModel) redisCacheTemplate.opsForValue().get(request.getSession().getId()); if (info == null || StringUtils.isEmpty(info)) { response.sendRedirect(request.getContextPath() + "/view/login"); return false; } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { } }

配置訪問路徑及靜態資源

/** * 登陸攔截控制類 * Created with IntelliJ IDEA. * Author: yangyongkang * Date: 2018/8/22 * Time: 14:17 */ @Configuration public class WebMvcConfig implements WebMvcConfigurer { @Autowired private UserSecurityInterceptor securityInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { InterceptorRegistration addInterceptor = registry.addInterceptor(securityInterceptor); // 排除配置 addInterceptor.excludePathPatterns("/error"); addInterceptor.excludePathPatterns("/static/**");//排除靜態資源 addInterceptor.excludePathPatterns("/view/login"); addInterceptor.excludePathPatterns("/login/check"); // 攔截配置 addInterceptor.addPathPatterns("/**"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");// } }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM