lee 2712 0 2017-03-18 18:27:26

文章位置:左搜> 编程技术> 正文
Java编程中spring boot项目动态添加拦截器Interceptor

1.自定义一个接口继承HandlerInterceptor接口

import org.springframework.web.servlet.HandlerInterceptor;

/**
 * url 拦截器
 * 
 * @author leftso
 *
 */
public interface UrlInterceptor extends HandlerInterceptor {

	String[] pathPatterns();
}
2.写一个配置类,动态添加自定义接口实现类实例的拦截器到容器中

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 添加自定义的拦截器
 * 
 * @author
 *
 */
@Configuration
public class MyMvcConfigurerAdapter extends WebMvcConfigurerAdapter {

	@Autowired
	SpringUtils springUtils;

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		super.addInterceptors(registry);
		@SuppressWarnings("static-access")
		Map<String, UrlInterceptor> urlInterceptors = springUtils.applicationContext
				.getBeansOfType(UrlInterceptor.class);
		Set<String> keys = urlInterceptors.keySet();
		Iterator<String> it = keys.iterator();
		while (it.hasNext()) {
			String key = it.next();
			UrlInterceptor urlInterceptor=urlInterceptors.get(key);
			registry.addInterceptor(urlInterceptor).addPathPatterns(urlInterceptor.pathPatterns());
		}

	}

}
(获取spring的容器请参照本站另外一篇博客http://www.leftso.com/blog/118.html
3.自己定义一个拦截器类,实现上面自己自定义的拦截接口

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;

@Component
public class MyInterceptor implements UrlInterceptor {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("Before....");
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		System.out.println("Doing....");

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		System.out.println("After....");

	}

	@Override
	public String[] pathPatterns() {
		return new String[] { "/**" };
	}

}
到这里就已经完成动态注入拦截器到容器中了。其他业务的拦截器只要实现自定义的拦截接口并用注解注解为spring组件就可以自动的被添加到容器中,不用每一次都去注册拦截器到spring容器中