Filter 过滤器
1、编写过滤器TestFilter 继承javax.servlet.Filter
@Component
public class TestFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("加载拦截器");
}
/**
* 过滤后的处理操作
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
System.out.println("开始拦截");
Date startTime = new Date();
//对请求进行处理
chain.doFilter(request,response);
Date endTime = new Date();
System.out.println("结束拦截");
System.out.println("总用时" + (endTime.getTime() - startTime.getTime()));
}
@Override
public void destroy() {
System.out.println("销毁拦截器");
}
}
注释:@Component注解把我们写好的Filter注入到Spring容器中
2、编写Controller,用于测试Filter
@RestController //spring boot注解 @RestController = @Controller + @ResponseBody
@RequestMapping("/test") //controller请求路径
public class TestController {
@GetMapping( "get_user")
public SR getUser() {
System.out.println("调用getUser服务");
User user = User.builder()
.age(16)
// .name("张三")
.sex("男")
.birthday(new Date())
.build();
return SR.ok(user);
}
}
运行服务测试,访问刚才写好的controller
我们的Filter已经拦截到了请求。
拦截器 Interceptor
1、编写拦截器TestInterceptor继承HandlerInterceptor
@Component
public class TestInterceptor implements HandlerInterceptor {
/**
* 进入controller方法之前调用
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("preHandle");
request.setAttribute("startTime",System.currentTimeMillis());
return true;
}
/**
* controller方法结束之后调用如果有controller方法有异常则不会调用
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("postHandler");
System.out.println(System.currentTimeMillis() - (Long)request.getAttribute("startTime")+ "秒");
}
/**
* controller方法之后调用
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("afterCompletion");
System.out.println(System.currentTimeMillis() - (Long)request.getAttribute("startTime")+ "秒");
}
}
写完拦截器我们对他进行注册,让Springboot能加载到,注册类
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private TestInterceptor testInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(testInterceptor);
}
}
启动服务访问接口:
下面进行postHandler异常测试
在控制器里随便抛出一个异常
结果:
在异常后面我们还会发现一组拦截到信息
这时候我们发现有postHandler,这是因为拦截器会拦截所有的controller,包括Spring自己的controller,后面就是在出现异常后Spring会进入一个ErrorController里。这时候就会被拦截了。