1、首先创建自定义拦截器类实现HandlerInterceptor接口:
public class LoginIntercepter 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 {
}
}
2、在配置类中注册自定义的拦截器(放行一些静态资源和首页界面)
@Configuration
public class AppConfig implements WebMvcConfigurer {
/*注册拦截器*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginIntercepter())
.addPathPatterns("/**")
.excludePathPatterns("/","/login","/css/**","/fonts/**","/js/**","/images/**");
}
}