Gitee仓库
https://gitee.com/Lin_DH/system
介绍
拦截器:拦截器是 Spring 框架提供的核心功能之一,主要用来拦截用户请求,在指定方法前后,根据业务需要执行预先设定的代码。
拦截器允许开发人员提前预定义一些逻辑,在用户请求、响应前后执行。也可以在用户请求前阻止其执行。
在拦截器中,开发人员可以在应用程序中做一些通用性的操作,比如通过拦截器来拦截前端发送的请求,判断 Session 中是否有登录用户的信息,如果有则放行,没有则进行拦截。
使用步骤
1)定义拦截器
实现 HandlerInterceptor 接⼝,并重写其所有方法。
- preHandle 方法:请求处理之前执行。返回 true,继续执行后续操作;返回 false,中断后续操作。
- postHandle 方法:请求处理之后,且视图处渲染之前执行。
- afterCompletion 方法:整个请求结束之后,视图渲染完毕后执行,最后执行。
2)注册配置拦截器
实现 WebMvcConfigurer 接口,并重写 addInterceptors 方法。
拦截器执行流程
代码实现
第一步:实现 HandlerInterceptor 接口,重写其所有方法。
LoginInterceptor.java
package com.lm.system.interceptor;import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/*** @author DUHAOLIN* @date 2024/11/12*/
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {log.info("校验用户登录信息");return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {log.info("返回用户信息");}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {log.info("视图渲染完毕后执⾏,最后执行");}}
第二步:实现 WebMvcConfigurer 接口,并重写 addInterceptors 方法。
WebConfig.java
package com.lm.system.config;import com.lm.system.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;import javax.annotation.Resource;/*** @author DUHAOLIN* @date 2024/11/12*/
@Configuration
public class WebConfig implements WebMvcConfigurer {//自定义拦截器对象@Resourceprivate LoginInterceptor loginInterceptor;@Overridepublic void addInterceptors(InterceptorRegistry registry) {//注册自定义拦截器对象registry.addInterceptor(loginInterceptor)//排除某些路径//.excludePathPatterns("/login", "/error")//设置拦截器拦截的请求路径(/** 表示拦截所有请求).addPathPatterns("/**");}
}
效果图
访问 Controller,发送请求。
控制台输出日志
2024-11-12 16:46:43 INFO 7740 org.apache.juli.logging.DirectJDKLog.log(DirectJDKLog.java:173) : Initializing Spring DispatcherServlet 'dispatcherServlet'
2024-11-12 16:46:43 INFO 7740 org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:525) : Initializing Servlet 'dispatcherServlet'
2024-11-12 16:46:43 INFO 7740 org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:547) : Completed initialization in 2 ms
2024-11-12 16:46:43 INFO 7740 com.lm.system.interceptor.LoginInterceptor.preHandle(LoginInterceptor.java:21) : 校验用户登录信息Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1a68bd5d] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1883892764 wrapping com.mysql.cj.jdbc.ConnectionImpl@1d1b0673] will not be managed by Spring
==> Preparing: SELECT id, `name`, age, gender, deleted, create_time, update_time FROM t_user WHERE deleted = 0
==> Parameters:
<== Columns: id, name, age, gender, deleted, create_time, update_time
<== Row: 1, Tom, 18, 男, 0, 2024-08-21 16:47:45, 2024-08-21 16:47:45
<== Row: 2, Joe, 20, 女, 0, 2024-08-21 16:47:58, 2024-08-21 16:47:58
<== Row: 3, Jim, 33, 女, 0, 2024-08-21 16:48:12, 2024-08-21 16:48:12
<== Total: 3
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1a68bd5d]
2024-11-12 16:46:43 INFO 7740 com.lm.system.common.ResultBody.getReturn(ResultBody.java:102) : {"status": 200,"msg": null,"count": 3,"data": [{"id": 1,"name": "Tom","age": 18,"gender": "男","create_time": "2024-08-21 16:47:45","update_time": "2024-08-21 16:47:45"},{"id": 2,"name": "Joe","age": 20,"gender": "女","create_time": "2024-08-21 16:47:58","update_time": "2024-08-21 16:47:58"},{"id": 3,"name": "Jim","age": 33,"gender": "女","create_time": "2024-08-21 16:48:12","update_time": "2024-08-21 16:48:12"}]
}2024-11-12 16:46:43 INFO 7740 com.lm.system.interceptor.LoginInterceptor.postHandle(LoginInterceptor.java:27) : 返回用户信息2024-11-12 16:46:43 INFO 7740 com.lm.system.interceptor.LoginInterceptor.afterCompletion(LoginInterceptor.java:32) : 视图渲染完毕后执⾏,最后执行
项目结构图
参考链接
Spring Boot实战:拦截器【https://blog.csdn.net/LHY537200/article/details/140947681】