HandleInteceptor拦截器做内容检查
设置拦截和放行区域
登录和静态资源放行,其他看session是否存在再考虑放行
定义inteceptors包中的LoginProtectInterceptor类
实现HandInterceptor接口
实现逻辑判断是否拦截
如果session中有userInfo,就放行,返回true;否则重定向到index首页,返回false。
LoginProtectInterceptor:
@Component
public class LoginProtectInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//false拦截 true执行
Object userInfo = request.getSession().getAttribute("userInfo");
if(userInfo !=null){
return true;
}else{
response.sendRedirect(request.getContextPath()+"index.html");
return false;
}
}
}
然后定义Interceptor的配置类:
MvcConfiguration:主要是配置拦截的路径 排除登录和资源路径
@Configuration
public class MvcConfiguration implements WebMvcConfigurer {
/**
* 用户注册拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
//拦截后台管理模块的路径 排除登录和资源路径
registry.addInterceptor(new LoginProtectInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/","/index.html","/index","/static/**",
"/user/login", "/user/logout",
"/api/**", "/css/**", "/images/**",
"/js/**", "/lib/**","/captcha"
);
}
}