SpringBoot 拦截器的简单配置及用法

拦截器的使用场景

      登陆验证、权限等都会用到拦截器

异步任务的简单配置

1.在任务类增加注解 @Configuration 继承 WebMvcConfigurerAdapter 代表配置拦截器的适配器

2.重写 addInterceptors 添加需要的拦截器地址及需要排除的拦截地址

实例

适配器中重写addInterceptors  配置我们需要拦截和不需要拦截的东西 注意:addPathPatterns("/*/**") 可以拦截所有请求  

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		/**
		 * 拦截器按照顺序执行
         *addPathPatterns 用于添加拦截规则
         *excludePathPatterns 用于排除拦截
		 */
		registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**")                                                                                                  
                                                     .excludePathPatterns("/three/**");
		registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/two/**")
													 .addPathPatterns("/one/**");
                                                     .addPathPatterns("/three/**");

		
		super.addInterceptors(registry);
	}

}

拦截器写法(以第一个拦截器为例)

public class OneInterceptor implements HandlerInterceptor  {

	/**
	 * 在请求处理之前进行调用(Controller方法调用之前)
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
			Object object) throws Exception {
		
		System.out.println("被one拦截,放行...");
		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
		
	}
}

猜你喜欢

转载自blog.csdn.net/qq_36014509/article/details/81453291
今日推荐