我们希望订单服务下的所有页面都必须登陆后才能访问,所以我们使用拦截器
来实现
1、编写我们自己的拦截器
package com.gulimall.order.interceptor;
import com.gulimall.common.constant.AuthServerConstant;
import com.gulimall.common.vo.MemberRespVo;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginUserInterceptor implements HandlerInterceptor {
public static ThreadLocal<MemberRespVo> threadLocal = new ThreadLocal<>();
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
MemberRespVo attribute = (MemberRespVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
if (attribute == null){ //未登录
request.getSession().setAttribute("msg", "请先进行登录!");
response.sendRedirect("http://auth.gulimall.com/login.html");
return false;
}else { //已登录
threadLocal.set(attribute);//放入threadLocal可以通用
return true;
}
}
}
2、把我们的拦截器加入Spring中
package com.gulimall.order.config;
import com.gulimall.order.interceptor.LoginUserInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class GulimallWebConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginUserInterceptor()).addPathPatterns("/**"); //加入我们自己写的拦截器
}
}
3、测试即可
如果未登录,就访问订单服务下的页面,就会跳转到登录页面。