[JAVAee]Spring拦截器

适用场景

像是页面的登录验证处理,权限校验,登录日志的处理.

实现步骤

  1. 创建⾃定义拦截器,实现 HandlerInterceptor 接⼝的 preHandle(执⾏具体⽅法之前的预处理⽅法.
  2. 将⾃定义拦截器加⼊ WebMvcConfigurer 的 addInterceptors ⽅法中.

下面以登录验证为例,实现拦截器.

实现HandlerInterceptor接口,并重写preHandle方法(在业务处理器处理请求之前被调用)

java 复制代码
@Component
public class Interceptor implements HandlerInterceptor {
    //preHandle方法返回true表示能通过,并继续执行原本的下一步.
    //返回false表示不能通过,执行其他程序或返回.
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession(false);
        if(session != null && session.getAttribute("user") != null){
            return true;//验证用户已为登录状态
        }
        //用户未登录
        response.sendRedirect("login.html");
        return false;
    }
}

实现WebMvcConfigurer接口,将上面实现的拦截器加入到其中

java 复制代码
@Configuration
public class MyConfig implements WebMvcConfigurer {
    @Autowired//注入拦截器的对象
    Interceptor Interceptor;

    @Override//添加拦截器
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(Interceptor)//将拦截器加入
                .addPathPatterns("/**")//拦截所有的方法
                .excludePathPatterns("/**/*.html")//放开(不拦截)以.html结尾的文件
                .excludePathPatterns("/user/login");//放开url为user/login的方法
    }
}
相关推荐
文丑颜不良啊3 小时前
LeetCode2821~2840题目解析
java·leetcode
apcipot_rain4 小时前
C++转Java日记(10)
java·开发语言
简 洁 冬冬5 小时前
泛型方法写法全面辨析:从「能编译」到「能跑」到「能用」
java·泛型
LGL6030A5 小时前
Java学习历程31——初识Spring Boot
java·spring boot·学习
Lansonli7 小时前
大数据Spark(八十八):Spark任务资源之Standalone集群测试
java·服务器·spark
budingxiaomoli7 小时前
Spring AOP
java·spring·java-ee
特立独行的猫A7 小时前
Ionic + 仓颉语言的 cj-tauri 开发框架实战:开发精美移动端 APP
java·后端·python
nice_lcj5207 小时前
LRU 缓存入门:它是什么、怎么用、面试怎么手写
java·数据结构·缓存·面试·lru
文丑颜不良啊8 小时前
LeetCode2741~2760题目解析
java·leetcode
金銀銅鐵18 小时前
带您看懂字节码指令(二):空循环里有什么
java·后端·ai编程