1、
首先先写一个拦截器类:需要实现HandlerInterceptor
public class MineIntegerceptor implements HandlerInterceptor
2、
重写preHandle等方法,实现功能:登录验证、权限验证等
public class MineIntegerceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
logger.info("====> Start: " + request.getRequestURI());
//判断用户ID是否存在,不存在就跳转到登录界面
Object user = request.getSession.getAttribute("loginUser");
if(user == null){
request.getRequestDispatcher("/login").forward(requset,response);
request.setAttribute("msg","登录失效,请重新登录");
return false;
}
return true;
}
}
3、
创建一个扩展Mvc配置类
在自己写的MvcConfig中,addInterceptors()添加自定义的拦截器
@Configuration
public class MyMvcConfig implements WebMvcConfigurer{
@Override
public void addInterceptors(InterceptorRegistry registry){
//addInterceptor 添加拦截器
//addPathPatterns 添加拦截的路径
//excludePathPatterns 添加拦截路径中 特殊放行的路径
registry.addInterceptor(new MineIntegerceptor())
.addPathPatterns("/**")
.excludePathPatterns("/custom");
}
}