springboot 登录拦截器
Posted 执笔coding
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot 登录拦截器相关的知识,希望对你有一定的参考价值。
1.定义一个视图解析器
@Configuration public class MyMvcConfig implements WebMvcConfigurer { /** * 添加视图解析 */ //// 无用代码,暂时注释,之后删除 // @Override // public void addViewControllers(ViewControllerRegistry registry) { // registry.addViewController("/").setViewName("index"); // registry.addViewController("/index.html").setViewName("index"); // registry.addViewController("/login.html").setViewName("login"); // registry.addViewController("/login").setViewName("login"); // registry.addViewController("/personal_center").setViewName("personal_center"); // } /** * 注册拦截器 */ @Override public void addInterceptors(InterceptorRegistry registry) { // registry.addInterceptor(new LoginInterceptor()) // .addPathPatterns("/**").excludePathPatterns("/index","/","/login","/user/login","/static/**","/druid/*"); InterceptorRegistration addInterceptor = registry.addInterceptor(new LoginInterceptor()); // 排除配置 addInterceptor.excludePathPatterns("/index"); addInterceptor.excludePathPatterns("/login"); addInterceptor.excludePathPatterns("/"); addInterceptor.excludePathPatterns("/error"); addInterceptor.excludePathPatterns("/static/**"); addInterceptor.excludePathPatterns("/pdb/tuba/**"); addInterceptor.excludePathPatterns("/test/**"); // 拦截配置 addInterceptor.addPathPatterns("/**"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); } }
2.定义一个拦截器
/** * 登录拦截器 */ public class LoginInterceptor implements HandlerInterceptor { /** * 在请求处理之前进行调用(Controller方法调用之前) */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws ServletException, IOException { Object user = request.getSession().getAttribute("user"); if (user==null){ request.setAttribute("error","当前处于未登录状态!"); // request.getRequestDispatcher("/").forward(request,response); response.sendRedirect("/index"); return false; }else { return true; } } /** * 请求处理之后进行调用,但是在视图被渲染之前(Controller方法调用之后) */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv) throws Exception { // TODO Auto-generated method stub } /** * 在整个请求结束之后被调用,也就是在DispatcherServlet 渲染了对应的视图之后执行 * (主要是用于进行资源清理工作) */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex) throws Exception { // TODO Auto-generated method stub } }
以上是关于springboot 登录拦截器的主要内容,如果未能解决你的问题,请参考以下文章