登录拦截器功能:开发一个系统时,系统需要登录后才能进行各种访问。如果没有登录,则没有权限进行访问,拦截器将拦截访问请求,跳转到登录页面提示用户进行登录。
编写一个拦截器实现handlerInterceptor接口
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String requestURI = request.getRequestURI();
log.info("拦截的请求:",requestURI);
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;
}
将拦截器添加到配置容器中
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginInterceptor())
.addPathPatterns("/**") //拦截所有请求,包括静态资源
.excludePathPatterns("/","/login","/css","/font","/image","/js","/picture","/webfonts"); //放行的请求
}
}