filter过滤器:过滤器始于servlet,依赖servlet,主要应用于用户访问权限、记录访问轨迹日志。
Interceptor拦截器:拦截器是基于java的反射机制,可以知晓要访问的contoller和方法。
AOP:Spring两大核心之一,可以获取访问的controller、方法和参数,但是获取不到请求头中的信息,主要应用于系统日志的记录。
三者同时存在于项目中,执行顺序为:filter、Interceptor、ControllerAdvice、Aspect、controller
基于spring boot框架REST拦截使用
Filter
之前提到过过滤器依赖于servlet容器,其运行原理与servlet类似,若想使用过滤器必须实现Filter接口,重写doFilter方法。Filter提供的方法有三个init、doFilter、destroy。
创建的TimeFilter主要是重写doFilter规定TimeFilter需要干哪些事情!
package com.per.web.filter;
import java.io.IOException;
import java.util.Date;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
//@Component
public class TimeFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("初始化filter");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
Long strat = new Date().getTime();
System.out.println("start filter");
chain.doFilter(request, response);
Long finish = new Date().getTime();
System.out.println("finish filter"+(finish-strat));
}
@Override
public void destroy() {
System.out.println("销毁filter");
}
}
WebConfig文件调用TimeFilter,并设定对哪些url的那种格式做过滤!
package com.per.web.config;
import java.util.ArrayList;
import java.util.List;
//import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
//import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
//import com.per.web.Interceptor.TimeInterceptor;
import com.per.web.filter.TimeFilter;
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
// @Autowired
// TimeInterceptor timeInterceptor;
//
// @Override
// public void addInterceptors(InterceptorRegistry registry) {
// registry.addInterceptor(timeInterceptor);
// }
@Bean
public FilterRegistrationBean timeFilter() {
FilterRegistrationBean filterRegistrationBean =new FilterRegistrationBean();
TimeFilter timeFilter =new TimeFilter();
filterRegistrationBean.setFilter(timeFilter);
List<String> urList =new ArrayList<String>();
urList.add("/*");
filterRegistrationBean.setUrlPatterns(urList);
return filterRegistrationBean;
}
}
Interceptor
拦截器需要实现HandlerInterceptor接口,重写里面的三种方法,preHandle、postHandle、afterCompletion。
preHandle:在拦截某个controller之前执行。
postHandle:在执行完controller之后不抛出异常的情况下执行。
afterCompletion:在执行完controller之后无论是否发生异常都会执行。
TimeInterceptor实现HandlerInterceptor接口。
/**
*
*/
package com.per.web.Interceptor;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
/**
* @author Administrator
*
*/
@Component
public class TimeInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// 在调用某个controller之前执行
System.out.println("preHandle");
System.out.println(((HandlerMethod)handler).getBean().getClass().getName());
System.out.println(((HandlerMethod)handler).getMethod().getName());
request.setAttribute("stratTime", new Date().getTime());
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// 在调用某个controller之后执行,且在不抛出异常的情况下
System.out.println("postHandle");
Long stratTime= (Long)request.getAttribute("stratTime");
request.setAttribute("控制层执行耗时:",(new Date()).getTime()-stratTime);
System.out.println("=================拦截器耗时:"+(Long)request.getAttribute("控制层执行耗时:"));
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// 执行controller之后执行,无论是否抛出异常
System.out.println("afterCompletion");
Long stratTime= (Long)request.getAttribute("stratTime");
request.setAttribute("控制层执行耗时:",(new Date()).getTime()-stratTime);
System.out.println("ex============"+ex);
}
}
配置文件注入TimeInterceptor,使用WebMvcConfigurerAdapter中的拦截器适配器添加该拦截器。
package com.per.web.config;
//import java.util.ArrayList;
//import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.web.servlet.FilterRegistrationBean;
//import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.per.web.Interceptor.TimeInterceptor;
//import com.per.web.filter.TimeFilter;
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter{
@Autowired
TimeInterceptor timeInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(timeInterceptor);
}
// @Bean
// public FilterRegistrationBean timeFilter() {
// FilterRegistrationBean filterRegistrationBean =new FilterRegistrationBean();
// TimeFilter timeFilter =new TimeFilter();
// filterRegistrationBean.setFilter(timeFilter);
//
// List<String> urList =new ArrayList<String>();
// urList.add("/*");
// filterRegistrationBean.setUrlPatterns(urList);
// return filterRegistrationBean;
// }
}
拦截器会拦截所有controller层,无论是自己写的还是spring提供的!!!
AOP
设置切点,前置、后置、增强
package com.per.web.aspect;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class TimeAspect {
@Around("execution(* com.per.web.controller.UserController.*(..))")
public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("切面编程开始!");
Object[] listObject=pjp.getArgs();
for(Object obj:listObject){
System.out.println("obj is============================"+obj);//遍历出执行的方法所有参数
}
Object obj=pjp.proceed();//执行切片
System.out.println(obj);//获取执行的方法
System.out.println("切面编程结束!");
return obj;
}
}
注意三个注解缺一不可,@Aspect、@Component、@Around(或@Before或After)