前置知识SpringBoot配置拦截器基于HandlerInterceptor接口实现,关键三个方法
preHandle()执行目标之前
postHandle()执行目标之后
afterCompletion()目标执行完后参数
拦截器实现
1.编写一个拦截器实现HandlerInterceptor接口
package com.b0.admin.interceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 实现功能登录检查
* 1.配置拦截器要拦截那些请求
* 2.把这些配置放在容器中
*/
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
/**
* 目标方法执行之前
*/
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURI = request.getRequestURI();
log.info("拦截的请求路径是{}",requestURI);
//登录检查逻辑
HttpSession session = request.getSession();
//判断session中是否存在loginUser,登录成功的用户会在session中加入loginUser对象
Object loginUser = session.getAttribute("loginUser");
if (loginUser!=null){
return true;
}
//拦截请求。未登录,跳转到登录页
//response.sendRedirect("/");//使用重定向传不过去msg信息,需要修改为请求转发
request.setAttribute("msg","请先登录!");
request.getRequestDispatcher("/").forward(request,response);
return false;
}
/**
* 目标方法执行之后
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("postHandle执行{}",modelAndView);
}
/**
* 目标方法页面渲染之后
*/
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("afterCompletion执行异常{}",ex);
}
}
2.拦截器注册到容器中,并指定拦截规则【如果拦截所有,静态资源也会被拦截】
通过编写配置类实现WebMvcConfigurer类重写addInterceptors()方法
package com.b0.admin.config;
import com.b0.admin.interceptor.LoginInterceptor;
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 AdminWebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**")// /** 表示拦截所有请求,静态资源也会被拦截
.excludePathPatterns("/","/login","/css/**","/fonts/**","/images/**","/js/**");//指定放行的请求
}
}