springboot 拦截器实现的具体步骤
程序员文章站
2022-05-02 18:59:28
...
拦截器的功能是拦截action请求,底层通过反射机制实现。
具体步骤:
(1)先写一个拦截器,实现HandlerInterceptor。拦截逻辑写在方法preHandle 里面,如果让通过 return true,否则return false。postHandle 是完成action请求后回到这个方法里面,这个时候还没渲染页面(没有展示页面)。afterCompletion 是渲染页面后执行的方法。
public class FirstInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
System.out.println("11########## FirstInterceptor 前前前前前前前前前前前前前前前前前前前前");
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
System.out.println("11########## FirstInterceptor 后后后后后后后后后后后后后后后后后后");
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
System.out.println("11########## FirstInterceptor over over over over");
}
}
(2)写一个配置类,加载拦截器。
@Configuration
public class SessionConfiguration extends WebMvcConfigurerAdapter{
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new FirstInterceptor()).addPathPatterns("/**");//拦截所有请求
super.addInterceptors(registry);
}
}
完成了。在拦截器的的preHandle return true 情况下,会如下图执行(return false 的情况下,会立即断掉,不往下执行,且无东西返回浏览器)。这个拦截器的顺序由配置类的registry.addInterceptor 先后顺序确定,先add的拦截器会越靠外,即越靠近浏览器。
推荐阅读