赞
踩
什么是拦截器:
想象一下你去一个需要门禁的办公楼,拦截器就像是那个门禁系统。当你(请求)想要进入办公楼(访问某个资源)时,门禁系统(拦截器)会先检查你是否符合条件(比如是否持有有效的门禁卡或是否已经通过身份验证)。如果符合条件,门禁系统会放行,让你进入办公楼;如果不符合条件,门禁系统会阻止你进入,并可能要求你进行其他操作(比如登记或联系相关人员)。
在SpringBoot中,拦截器就是这样一种机制,它可以在请求到达控制器之前或之后“拦截”请求,并根据预定义的规则对请求进行处理。
拦截器在SpringBoot中主要有以下几个作用:
1.2拦截器的基本使用
1.⾃定义拦截器:实现HandlerInterceptor接⼝,并重写其所有⽅法
- @Slf4j
- @Component
- public class LoginInterceptor implements HandlerInterceptor {
-
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse
- response, Object handler) throws Exception {
- log.info("LoginInterceptor ⽬标⽅法执⾏前执⾏..");
- return true;
- }
- @Override
- public void postHandle(HttpServletRequest request, HttpServletResponse
- response, Object handler, ModelAndView modelAndView) throws Exception {
- log.info("LoginInterceptor ⽬标⽅法执⾏后执⾏");
- }
- @Override
- public void afterCompletion(HttpServletRequest request,
- HttpServletResponse response, Object handler, Exception ex) throws Exception {
- log.info("LoginInterceptor 视图渲染完毕后执⾏,最后执⾏");
- }
- }
2.注册配置拦截器:实现WebMvcConfigurer接⼝,并重写addInterceptors⽅法
- @Configuration
- public class WebConfig implements WebMvcConfigurer {
- //⾃定义的拦截器对象
- @Autowired
- private LoginInterceptor loginInterceptor;
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- //注册⾃定义拦截器对象
- registry.addInterceptor(loginInterceptor)
- .addPathPatterns("/**");//设置拦截器拦截的请求路径( /** 表⽰拦截所
- 有请求)
- }
- }
可以看到, 拦截器拦截了请求, 没有进⾏响应.
上述代码中, 我们配置的是 /** , 表⽰拦截所有的请求.
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
- @Configuration
- public class WebConfig implements WebMvcConfigurer {
- //⾃定义的拦截器对象
- @Autowired
- private LoginInterceptor loginInterceptor;
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- //注册⾃定义拦截器对象
- registry.addInterceptor(loginInterceptor)
- .addPathPatterns("/**")
- .excludePathPatterns("/user/login");//设置拦截器拦截的请求路径
- (/** 表⽰拦截所有请求)
- }
- }
以上拦截规则可以拦截此项⽬中的使⽤ URL,包括静态⽂件(图⽚⽂件, JS 和 CSS 等⽂件)
有了拦截器之后,会在调⽤ Controller 之前进⾏相应的业务处理,执⾏的流程如下图
- import com.example.demo.constant.Constants;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.stereotype.Component;
- import org.springframework.web.servlet.HandlerInterceptor;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import javax.servlet.http.HttpSession;
- @Slf4j
- @Component
- public class LoginInterceptor implements HandlerInterceptor {
- @Override
- public boolean preHandle(HttpServletRequest request, HttpServletResponse
- response, Object handler) throws Exception {
- HttpSession session = request.getSession(false);
- if (session != null &&
- session.getAttribute(Constants.SESSION_USER_KEY) != null) {
- return true;
- }
- response.setStatus(401);
- return false;
- }
- }
http状态码401: UnauthorizedIndicates that authentication is required and was either not provided or has failed. If therequest already included authorization credentials, then the 401 status code indicates thatthose credentials were not accepted.中⽂解释: 未经过认证. 指⽰⾝份验证是必需的, 没有提供⾝份验证或⾝份验证失败. 如果请求已经包含授权凭据,那么401状态码表⽰不接受这些凭据
2.注册配置拦截器
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
- import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
- @Configuration
- public class WebConfig implements WebMvcConfigurer {
- //⾃定义的拦截器对象
- @Autowired
- private LoginInterceptor loginInterceptor;
- @Override
- public void addInterceptors(InterceptorRegistry registry) {
- //注册⾃定义拦截器对象
- registry.addInterceptor(loginInterceptor)
- .addPathPatterns("/**")//设置拦截器拦截的请求路径(/**表⽰拦截所有请
- 求)
- .excludePathPatterns("/user/login")//设置拦截器排除拦截的路径
- .excludePathPatterns("/**/*.js") //排除前端静态资源
- .excludePathPatterns("/**/*.css")
- .excludePathPatterns("/**/*.png")
- .excludePathPatterns("/**/*.html");
- }
- }
- @RequestMapping("/getListByPage")
- public Result getListByPage(PageRequest pageRequest, HttpSession session) {
- log.info("获取图书列表, pageRequest:{}", pageRequest);
- // //判断⽤⼾是否登录
- // if (session.getAttribute(Constants.SESSION_USER_KEY)==null){
- // return Result.unlogin();
- // }
- // UserInfo userInfo = (UserInfo)
- session.getAttribute(Constants.SESSION_USER_KEY);
- // if (userInfo==null || userInfo.getId()<0 ||
- "".equals(userInfo.getUserName())){
- // return Result.unlogin();
- // }
- //⽤⼾登录, 返回图书列表
- PageResult<BookInfo> pageResult =
- bookService.getBookListByPage(pageRequest);
- log.info("获取图书列表222, pageRequest:{}", pageResult);
- return Result.success(pageResult);
- }
4运⾏程序, 通过Postman进⾏测试:
4.1查看图书列表
4.2登录
4.3再次查看图书列表
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。