在Java的服务端开发当中,拦截器是很常见的业务场景,这里对Java开发当中几种常见的拦截器的实现方式进行记录和分析。案例说明基于Spring Boot环境。
一:实现接口(使用过滤器方式拦截请求)
import ;
import .*;
import ;
import ;
@Component
public class TimeInterceptor implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
("time filter init");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
("time filter start");
long start = new Date().getTime();
(servletRequest, servletResponse);
("time filter 耗时:"+(new Date().getTime()-start));
("time filter finish");
}
@Override
public void destroy() {
("time filter destroy");
}
}
如使用@Compent注解声明不需要加入其它配置即可使得拦截器生效,但是默认拦截/*,会拦截所有请求。
二:使用@Bean注入自定义拦截器,依然上面的代码,去掉@Compent注解,创建TimeWebConfig配置类:
import ;
import ;
import ;
import ;
import ;
@Configuration
public class TimeWebConfig {
@Bean
public FilterRegistrationBean timeFilter(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
TimeInterceptor interceptor = new TimeInterceptor();
(interceptor);
List<String> urls = new ArrayList<>();
("/user/*");
(urls);
return registrationBean;
}
}
上面这两种拦截请求的实现是基于JavaEE提供的Filter接口实现的,缺点在于,该拦截器实际上是一个过滤器,执行代码的方法doFilter只提供了request,response等参数,当请求进入被过滤器拦截的时候,我们并不知道这个请求是由哪个控制器的哪个方法来执行的。
三:使用springMVC提供的拦截器,实现接口:
创建自定义的拦截器:
import ;
import ;
import ;
import ;
import ;
import ;
import ;
@Component
public class MyInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object handler) throws Exception {
("preHandler");
(((HandlerMethod) handler).getBean().getClass().getName());
(((HandlerMethod) handler).getMethod().getName());
("start", new Date().getTime());
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
("postHandler");
Long start = (Long) ("start");
("time interceptor 耗时:"+(new Date().getTime()-start));
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
("afterCompletion");
Long start = (Long) ("start");
("time interceptor 耗时:"+(new Date().getTime()-start));
("ex is:"+e);
}
}
创建配置类:
import ;
import ;
import ;
import ;
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
@Autowired
private MyInterceptor interceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
(interceptor).addPathPatterns("/user/*").excludePathPatterns("/blog/*");
}
}
此种方式的拦截器当中我们能够获取拦截的请求对应的类和方法的相关信息,缺点在于该handler对象无法获取具体执行方法的参数信息。
四:利用Spring的切面(AOP)实现拦截器:
引入jar包:
<!-- /artifact//spring-boot-starter-aop -->
<dependency>
<groupId></groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
创建切片类:
import ;
import ;
import ;
import ;
import ;
@Aspect
@Component
public class TimeAspect {
@Around("execution(* .*(..))")
public Object handlerControllerMethod(ProceedingJoinPoint point) throws Throwable {
("time aspect start");
long start = new Date().getTime();
Object[] args = ();
for (Object obj : args) {
("arg is:"+obj);
}
Object obj = ();//具体方法的返回值
("aspect 耗时:"+(new Date().getTime()-start));
("time aspect end");
return obj;
}
}
aspectj基于AOP实现的拦截器功能十分强大,具体详解请参考spring官网网站的文档。