今天就是把有关拦截器的知识做一个总结。
推荐观看
大厂面试真题集结地:阿里三面+腾讯二面+支付宝三面+拼多多二面+字节四面+淘宝五面_哔哩哔哩 (゜-゜)つロ 干杯~-bilibiliwww.bilibili.com
厉害了!B站最全网络底层汇总:TCP、Sockt、三次握手、四次挥手、NIO、Epoll、多路复用(附赠源码、脑图)www.bilibili.com
阿里资深架构师讲解最“细”的spring源码(附赠讲课资料和源码)www.bilibili.com
Java架构师必会六大核心知识点:多线程、JVM、设计模式、MySQL、Redis、ZooKeeperwww.bilibili.com
你从未听过的全新版本!Tomcat、TCP/IP、IO、分布式微服务架构全解www.bilibili.com
1.拦截器概述
1.1 什么是拦截器?
Spring MVC中的拦截器(Interceptor)类似于Servlet中的过滤器(Filter),它主要用于拦截用户请求并作相应的处理。例如通过拦截器可以进行权限验证、记录请求信息的日志、判断用户是否登录等。
要使用Spring MVC中的拦截器,就需要对拦截器类进行定义和配置。通常拦截器类可以通过两种方式来定义。
1.通过实现HandlerInterceptor接口,或继承HandlerInterceptor接口的实现类(如HandlerInterceptorAdapter)来定义。
2.通过实现WebRequestInterceptor接口,或继承WebRequestInterceptor接口的实现类来定义。
以实现HandlerInterceptor接口方式为例,自定义拦截器类的代码如下:
public class CustomInterceptor implements HandlerInterceptor{
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler)throws Exception {
return false;
}
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler,
Exception ex) throws Exception {
}
}
上述代码中,自定义拦截器实现了HandlerInterceptor接口,并实现了接口中的