Springboot项目使用拦截器方法详解

  

1。创建一个拦截器并实现HandlerInterceptor接口

        包com.leiyuan.bs.interceptor;      进口org.springframework.web.servlet.HandlerInterceptor;   进口org.springframework.web.servlet.ModelAndView;      进口javax.servlet.http.HttpServletRequest;   进口javax.servlet.http.HttpServletResponse;//拦截器   公共类MyHandlerInterceptor实现HandlerInterceptor {/* *   *拦截(控制器方法调用之前)   *   * @param请求请求   * @param反应反应   * @param o o   * @return通过与否   * @throws异常异常处理   */@Override   公共布尔preHandle (HttpServletRequest请求,HttpServletResponse响应对象   {o)抛出异常//TODO我这里是通过用户是否登陆进行拦截,我的用户信息存储在会话中,名称为userSession,大家可以自行实现   如果(request.getSession () .getAttribute (userSession)==null) {//拦截至登陆页面   request.getRequestDispatcher (“/user/toLogin”)。提出(请求、响应);//错误为不通过   返回错误;   }//真正为通过   返回true;   }//此方法为处理请求之后调用(调用过控制器方法之后,跳转视图之前)   @Override   公共空postHandle (HttpServletRequest HttpServletRequest HttpServletResponse HttpServletResponse,对象啊,   {ModelAndView ModelAndView)抛出异常      }//此方法为整个请求结束之后进行调用   @Override   公共空afterCompletion (HttpServletRequest HttpServletRequest HttpServletResponse HttpServletResponse,   对象o,异常e)抛出异常{      }   }      

2。创建一个配置类MyHandlerInterceptorConfig并继承WebMvcConfigurerAdapter类重写addInterceptors (InterceptorRegistry注册表)方法

        包com.leiyuan.bs;      进口com.leiyuan.bs.interceptor.MyHandlerInterceptor;   进口org.springframework.stereotype.Component;   进口org.springframework.web.servlet.config.annotation.InterceptorRegistry;   进口org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;//拦截器配置类   @ component   公开课MyHandlerInterceptorConfig延伸WebMvcConfigurerAdapter {   @Override   公共空间addInterceptors (InterceptorRegistry注册表){/* *   *这里的addPathPatterns(“/* *”)为配置需要拦截的方法“/* *”代表所有,而后excludePathPatterns (“/user/toLogin”)等方法为排除哪些方法不进行拦截   */注册表。addInterceptor(新MyHandlerInterceptor ()) .addPathPatterns (“/* *”) .excludePathPatterns .excludePathPatterns (“/user/toLogin”)   (“/user/登录”).excludePathPatterns .excludePathPatterns (“/user/toNewUser”) (“/user/分类列出”);   super.addInterceptors(注册表);   }   }      

3。启动项目即可看到效果了

  

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

Springboot项目使用拦截器方法详解