WebConfig
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;
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;
/**
* User: ldj
* Date: 2022/10/12
* Time: 10:37
* Description: 访问order服务,都要经过拦截器
*/
@Configuration
public class MyWebConfig implements WebMvcConfigurer {
@Autowired
private LoginUserInterceptor loginUserInterceptor;
/**
* 根据请求url进行配置,/**代表当前项目任意请求到达目标方法前都会被拦截审核,是否放行
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginUserInterceptor)
.addPathPatterns("/**")
.excludePathPatterns(
"/order/order/status/**",
"/mq/message/update/consumed/**",
"/payed/notify");
}
}
Interceptor
import com.atguli.common.constant.AuthServerConstant;
import com.atguli.common.vo.MemberRespVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* User: ldj
* Date: 2022/10/12
* Time: 10:31
* Description: 将拦截器作为组件交给spring容器,要让拦截器组件生效,
* 还需配置WebMvcConfigurer,重写addInterceptors方法添加拦截器组件 //interceptor.path.uris=/kill,/**
*/
@Component
@RefreshScope
public class LoginUserInterceptor implements HandlerInterceptor {
//拦截器存储当前线程共享变量数据
public static ThreadLocal<MemberRespVO> threadLocal = new ThreadLocal<>();
//添加需要拦截的请求uri,也可以在WebConfig配置
@Value("#{'${spring.interceptor.uris}'.split(',')}")
private List<String> uris;
/**
* 在请求到达目标方法之前拦截业务判断,是否放行请求?
*/
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) throws Exception {
String uri = request.getRequestURI();
AntPathMatcher antPathMatcher = new AntPathMatcher();
boolean match = false;
if (uris.size() != 0) {
for (String ur : uris) {
if (antPathMatcher.match(ur, uri)) {
match = true;
break;
}
}
}
if (match) {
//当前请求需要用户登录才能放行,默认拿到Cookie的sessionId
MemberRespVO loginUser = (MemberRespVO) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
if (loginUser != null) {
//将用户的登录信息存入threadLocal,为执行当前请求的线程所共享
threadLocal.set(loginUser);
return true;
} else {
//没登录,要去登录
request.getSession().setAttribute("msg", "请先登录再访问");
response.sendRedirect("http://auth.gulimall.com/login.html");
return false;
}
}
return true;
}
}