- 定义拦截器
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {
@Override // 目标资源方法执行前执行,返回true:放行,返回false:不放行
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("preHandle...");
/**
* 此处可以写相应逻辑,满足条件返回true进行放行,不满足条件返回false进行拦截
*/
return true;
}
@Override // 目标资源方法执行后执行
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
log.info("postHandle...");
}
@Override // 视图渲染完毕后执行,最后执行
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
log.info("afterCompletion...");
}
}
- 注册拦截器
import com.xiaofeixiang.interceptor.LoginCheckInterceptor;
import lombok.extern.slf4j.Slf4j;
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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Slf4j
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired // 注入上边定义的拦截器
private LoginCheckInterceptor loginCheckInterceptor;
/**
* 打开拦截器
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
log.info("拦截器启动成功。。。。");
// 拦截所有请求
registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**");
}
}
至此拦截器添加成功