在springBoot只给你如果不设置登录拦截器的话,在任何情况下都可以访问该项目中的所有资源
- 拦截器主要方法两个
1.LoginInterceptor 主要继承HandlerInterceptor 类来实现
package com.example.erp_project.config;
import com.example.erp_project.entity.UserEntity;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
/**
* @author Lolo don‘t feel
*/
@Component
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession session = request.getSession();
//从seesion中取出当前登录的信息,
Object account = session.getAttribute("phone");
//如果为空跳转到登录页面,并弹出提示信息
if (account == null) {
//System.out.println("用户未登陆");
//PageController中会跳转到同名的页面
response.sendRedirect("login");
return false;
} else {
return true;
}
}
}
2.WebConfigurer 主要继承WebMvcConfigurer 类实现
package com.example.erp_project.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author Lolo don‘t feel
*/
@Configuration
public class WebConfigurer implements WebMvcConfigurer {
@Autowired
private LoginInterceptor loginInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
//拦截所有的资源addPathPatterns("/**"),释放登陆相关的资源excludePathPatterns(
registry.addInterceptor(loginInterceptor).addPathPatterns("/**").excludePathPatterns(
"/js/**", "/layui/**", "/dist/sliderVerify/**","/lib/**","/css/**",
"/images/**", "/register", "/login", "/restPassword",
"/agreement","/auth/login","/auth/register","/auth/restPassword"
);
}
}