一、创建一个EmployeeIntercepto自定义拦截器类,实现HandlerInterceptor接口
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Slf4j
@Component
public class EmployeeInterceptor implements HandlerInterceptor {
}
二、在EmployeeIntercepto自定义拦截器类重写preHandle方法
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Component
public class EmployeeInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
log.info("本次请求的地址 {}",request.getRequestURI());
if (request.getSession().getAttribute("Employee")!=null){
return true;
}
return false;
}
}
三、创建InterceptorConfiguration拦截器配置类
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfiguration implements WebMvcConfigurer {
}
四、在InterceptorConfiguration拦截器配置类重写addInterceptors方法
import com.itheima.fliter.EmployeeInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfiguration implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
InterceptorRegistration registration = registry.addInterceptor(new EmployeeInterceptor());
registration.addPathPatterns("/**");
registration.excludePathPatterns(
"/backend/**",
"/employee/login");
}
}