✅P265_商城业务-订单服务-订单登录拦截
2024/2/14大约 1 分钟
编写拦截器
用户结算、查看订单必须是已经登录状态,通过编写一个拦截器进行判断,用户登录放行,用户未登录跳转到登录页面
cfmall-order/src/main/java/com/gyz/cfmall/order/interceptor/LoginUserInterceptor.java
package com.gyz.cfmall.order.interceptor;
import com.gyz.common.constant.AuthServerConstant;
import com.gyz.common.vo.MemberResponseVo;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author gong_yz
* @Description 订单结算拦截器
*/
public class LoginUserInterceptor implements HandlerInterceptor {
public static ThreadLocal<MemberResponseVo> loginUser = new ThreadLocal<>();
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
MemberResponseVo attribute = (MemberResponseVo) request.getSession().getAttribute(AuthServerConstant.LOGIN_USER);
if (attribute != null) {
loginUser.set(attribute);
return true;
} else {
request.getSession().setAttribute("msg", "请先进行登录");
response.sendRedirect("http://auth.cfmall.com/login.html");
return false;
}
}
}
编写配置类使得拦截器生效
cfmall-order/src/main/java/com/gyz/cfmall/order/config/CfMallWebConfig.java
package com.gyz.cfmall.order.config;
import com.gyz.cfmall.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;
import javax.annotation.Resource;
/**
* @author gong_yz
* @Description 拦截器配置类
*/
@Configuration
public class CfMallWebConfig implements WebMvcConfigurer {
@Resource
private LoginUserInterceptor loginUserInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(loginUserInterceptor).addPathPatterns("/**");
}
}
前端页面
路由跳转:点击去结算跳转至订单确认页
cfmall-cart/src/main/resources/templates/cartList.html
对应接口:cfmall-order/src/main/java/com/gyz/cfmall/order/web/OrderWebController.java
@Controller
public class OrderWebController {
@GetMapping("/toTrade")
public String toTrade() {
return "confirm";
}
}
未登录进行消息提醒
cfmall-auth-server/src/main/resources/templates/login.html
<span style="color: red" th:if="${session.loginUser!=null}">[[${session.msg}]]</span>
测试
商城首页,点击右上方“我的购物车”,点击“去结算”,就会跳转到订单确认页面。