序言:几乎所有项目都需要拦截器,所以小伙伴们必须要掌握这门技术哦,不然只会mybaits增删改查那是实习生干的活呀。
1、创建拦截器类,implements HandlerInterceptor
public class MyIncerteptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("进入拦截器"); HttpSession session = request.getSession(); Admin user = (Admin) request.getSession().getAttribute("ADMIN_ACCOUNT"); if (user == null) { //用户为空,重新登录 response.sendRedirect(request.getContextPath() + "/login.html"); return false; } return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { } }
2、配置文件,注册拦截器 implements
@Configuration public class InterceptorConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { String[] addPathPatterns ={ "/dtb/**" }; String[] excludePathPatterns ={ "/test/**" }; InterceptorRegistration interceptorRegistration = registry.addInterceptor(new MyIncerteptor()); interceptorRegistration.addPathPatterns(addPathPatterns); interceptorRegistration.excludePathPatterns(excludePathPatterns); } }
addPathPatterns是拦截的那些目录,excludePathPatterns不拦截的路径,上面我们可以换一种常用的写法,只不过上面看上去更明白,interceptorRegistration获取的注册对象添加拦截器,并设置拦截路径
@Configuration public class InterceptorConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { String[] addPathPatterns ={ "/dtb/**" }; String[] excludePathPatterns ={ "/test/**" }; registry.addInterceptor(new MyIncerteptor()).addPathPatterns(addPathPatterns).excludePathPatterns(excludePathPatterns); } }
在优化一下,可以写成:
@Configuration public class InterceptorConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyIncerteptor()).addPathPatterns("/dtb/**").excludePathPatterns("/test/**"); } }
成功!其实就两个类就可以了。
3、注意点:
springboot2.0以后:使用spring5,废弃了WebMvcConfigurerAdapter,解决方案 implements WebMvcConfigurer
springboot2.0之前,1.X版本,使用spring4,使用拦截器需要 extends WebMvcConfigurerAdapter
转载于:https://my.oschina.net/mdxlcj/blog/1858710