一。实现商品详情展示
1.测试获取后台当个商品的信息
2.实现通过点击商品名称和商品图片进入商品详情页面
1)查找出商品信息
2)在前端进行映射
3)设置库存选择限制
判断逻辑
$(function(){ //给type绑定点击事件 $(".type").click(function () { var index = $(".type").index(this); var obj = $(".type").eq(index); $(".type").removeClass("checked"); obj.addClass("checked"); }); //给color绑定点击事件 $(".color").click(function () { var index = $(".color").index(this); var obj = $(".color").eq(index); $(".color").removeClass("checked"); obj.addClass("checked"); }); }); //商品数量++ function increase() { var value = $("#quantity").val(); var stock = $("#stock").text(); value++; if(value > stock){ value = stock; } $("#quantity").val(value); } //商品数量-- function reduce() { var value = $("#quantity").val(); value--; if(value == 0){ value = 1; } $("#quantity").val(value); } 二.接下里处理加入购物车的功能
1.商品选择以后创建相对应信息将数据存入数据库
需要将数据库以及product实体类里面的cost改为浮点型便于后面计算
private Float cost;
1)编写CartController
@Controller @RequestMapping("/cart") public class CartController { @Autowired private CartService cartService; @GetMapping("/add/{productId}/{price}/{quantity}") public ModelAndView add( @PathVariable("productId") Integer productId, @PathVariable("price") Float price, @PathVariable("quantity") Integer quantity, HttpSession session ){ Cart cart = new Cart(); cart.setProductId(productId); cart.setQuantity(quantity); cart.setCost(price*quantity); User user = (User) session.getAttribute("user"); cart.setUserId(user.getId()); ModelAndView modelAndView = new ModelAndView(); if (cartService.save(cart)){ modelAndView.setViewName("settlement1"); } return modelAndView; } }
对应映射前端
对应add的方法
//添加购物车 function addCart(productId,price){ var quantity = $("#quantity").val(); window.location.href="/cart/add/"+productId+"/"+price+"/"+quantity; }
测试注意清理缓存
选择2个数量添加到购物车
存入数据库
跳转到订单详情这个页面还没进行映射处理所以显示的是死数据
2)接来下进行未登录时候选中添加出现的异常情况报错添加过滤器
[1]添加过滤器实现类UserFilter
package com.redhat.mmall002.filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class UserFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; HttpSession session = request.getSession(); if (session.getAttribute("user")==null){ response.sendRedirect("/productCategory/list"); }else { filterChain.doFilter(servletRequest,servletResponse); } } }
2)配置需要过滤的对象FilterConfig
package com.redhat.mmall002.config; import com.redhat.mmall002.filter.UserFilter; import org.springframework.boot.web.servlet.AbstractFilterRegistrationBean; import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class FilterConfig { @Bean public AbstractFilterRegistrationBean filterRegistrationBean(){ FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(); filterRegistrationBean.setFilter(new UserFilter()); filterRegistrationBean.addUrlPatterns("/cart/add/*"); return filterRegistrationBean; } } 未登录时候测试访问直接返回首页
已登录账户加入直接进入订单详情
3)购物车减库存操作服务实现层CartServiceImpl
@Service public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService { @Autowired private CartMapper cartMapper; @Autowired public ProductMapper productMapper; @Override public boolean save(Cart entity) { //扣库存 Product product = productMapper.selectById(entity.getProductId()); Integer stock = product.getStock()-entity.getQuantity(); product.setStock(stock); productMapper.updateById(product); if (cartMapper.insert(entity)==1){ return true; } return false; } }
打断点测试
操作之前
操作后
4)自定义购买数量超出总数或者没有商品了时抛出异常
【1】 CartServiceImpl实现层代码
@Service @Slf4j public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService { @Autowired private CartMapper cartMapper; @Autowired public ProductMapper productMapper; @Override public boolean save(Cart entity) { //扣库存 Product product = productMapper.selectById(entity.getProductId()); Integer stock = product.getStock()-entity.getQuantity(); if (stock < 0){ log.error("[添加购物车]库存不足!stock={}",stock); throw new MallException(ResultEnum.STOCK_ERROR); } product.setStock(stock); productMapper.updateById(product); if (cartMapper.insert(entity)==1){ return true; } return false; } }
【2】CartController抛出异常页面路径跳转
@Controller @RequestMapping("/cart") public class CartController { @Autowired private CartService cartService; @GetMapping("/add/{productId}/{price}/{quantity}") public String add( @PathVariable("productId") Integer productId, @PathVariable("price") Float price, @PathVariable("quantity") Integer quantity, HttpSession session ){ Cart cart = new Cart(); cart.setProductId(productId); cart.setQuantity(quantity); cart.setCost(price*quantity); User user = (User) session.getAttribute("user"); cart.setUserId(user.getId()); try { if (cartService.save(cart)){ return "settlement1"; } } catch (Exception e) { return "redirect:/productCategory/list"; } return null; } }
【3】前端弹框显示
//添加购物车 function addCart(productId,price){ var stockStr = $("#stock").text(); var stock = parseInt(stockStr); if (stock==0){ alert("库存不足!") return false; } var quantity = $("#quantity").val(); window.location.href="/cart/add/"+productId+"/"+price+"/"+quantity; }
【4】创建枚举类
package com.redhat.mmall002.enums; import lombok.Getter; @Getter public enum ResultEnum { STOCK_ERROR(1,"库存不足"); private Integer code; private String msg; ResultEnum(Integer code, String msg) { this.code = code; this.msg = msg; } }
【5】创建异常处理
package com.redhat.mmall002.exception; import com.redhat.mmall002.enums.ResultEnum; public class MallException extends RuntimeException { public MallException(String error){ super(error); } public MallException(ResultEnum resultEnum){ super(resultEnum.getMsg()); } } 最后创造一个库存为零的测试
三.完成最后订单详情的页面调用
1.完成后台数据封装前端需要数据调用查询
1)新建CartVO类封装需要的数据
package com.redhat.mmall002.vo; import lombok.Data; @Data public class CartVO { private Integer id; private Integer quantity; private Float cost; private String name; private Float price; private String fileName; }
2)CartService类里面定义查询方法
public List<CartVO> findAllCartVOByUserId(Integer id);
public interface CartService extends IService<Cart> { public List<CartVO> findAllCartVOByUserId(Integer id); }
3)CartServiceImpl类重写需要对应实现的方法
@Override public List<CartVO> findAllCartVOByUserId(Integer id) { List<CartVO> cartVOList = new ArrayList<>(); QueryWrapper wrapper = new QueryWrapper(); wrapper.eq("user_id",id); List<Cart> cartList = cartMapper.selectList(wrapper); for (Cart cart :cartList){ CartVO cartVO = new CartVO(); BeanUtils.copyProperties(cart,cartVO); Product product = productMapper.selectById(cart.getProductId()); BeanUtils.copyProperties(product,cartVO); cartVOList.add(cartVO); } return cartVOList; } }
4)go-to测试类测试功能是否实现
package com.redhat.mmall002.service; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest class CartServiceTest { @Autowired private CartService cartService; @Test void findAllCartVOByUserId(){ cartService.findAllCartVOByUserId(12).forEach(System.out::println); } }
测试结果
2.实现对应前端的映射
1)后端查找所有购物车路径CartController类里面添加
@GetMapping("/findAllCart") public ModelAndView findAllCart(HttpSession session){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("settlement1"); User user = (User) session.getAttribute("user"); modelAndView.addObject("list",cartService.findAllCartVOByUserId(user.getId())); return modelAndView; } } 前面在执行保存创建订单的时候返回
return "redirect:/cart/findAllCart";
2)前端迭代映射
加完购物车测试商品详情页面
加上前面的测试数据完成查找并且显示