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