实现拦截器需要实现HandlerInterceptor接口,接口中有三个方法用于网页加载的不同阶段
首先写一个拦截器的类LoginInterceptor
/**
* 1.配置好拦截器要拦截哪些请求
* 2.把这些配置放在容器中
* 3.指定拦截规则
* */
public class LoginInterceptor implements HandlerInterceptor {
//目标方法执行之前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//登陆检查逻辑
HttpSession session = request.getSession();
Object loginUser = session.getAttribute("loginUser");
if(loginUser != null){
//放行
return true;
}
//拦截
request.setAttribute("msg","请先登陆");
request.getRequestDispatcher("/login").forward(request,response);
return false;
}
//目标方法执行完成以后
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
//页面渲染以后
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
之后在webmvc配置类中对拦截器进行配置,所有的mvc配置类需要实现WebMvcConfigurer接口,在WebMvcConfigurer接口中有一个方法是addInterceptors,用来添加拦截器
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**") //默认拦截的请求 一般都是些/**
.excludePathPatterns(
"/",
"/login",
"/css/**",
"/fonts/**",
"/images/**",
"/js/**"
);//放行的内容
}
}