【基于SprintBoot+Mybatis+Mysql】电脑商城项目之商品热销排行及显示商品详情

🧸安清h:个人主页 

   🎥个人专栏:【Spring篇】【计算机网络】【Mybatis篇】

🚦作者简介:一个有趣爱睡觉的intp,期待和更多人分享自己所学知识的真诚大学生。


目录

🚀1.商品热销排行-创建数据表

🚀2.商品热销排行-创建实体类

🚀3.商品热销排行-持久层

✨3.1规划需要执行的SQL语句

✨3.2接口和抽象方法 

✨3.3配置映射

🚀4.商品热销排行-业务层

✨4.1规划异常

 ✨4.2接口与抽象方法

✨4.3实现抽象方法

🚀5.商品热销排行-控制层

✨5.1处理异常

✨5.2设计请求

✨5.3处理请求

🚀6.商品热销排行-前端页面

🎯1.显示商品详情-持久层

✨1.1规划需要执行的SQL语句

✨1.2接口与抽象方法

✨1.3配置SQL映射

🎯2.显示商品详情-业务层

✨2.1规划异常

✨2.2接口和抽象方法

✨2.3实现抽象方法

🎯3.显示商品详情-控制层

✨3.1处理异常

✨3.2设计请求

✨3.3处理请求

🎯4.显示商品详情-前端页面


🚀1.商品热销排行-创建数据表

1.使用use命令先选中store数据库。

use store

2.在store数据库中创建t_product数据表。

CREATE TABLE t_product (
  id int(20) NOT NULL COMMENT '商品id',
  category_id int(20) DEFAULT NULL COMMENT '分类id',
  item_type varchar(100) DEFAULT NULL COMMENT '商品系列',
  title varchar(100) DEFAULT NULL COMMENT '商品标题',
  sell_point varchar(150) DEFAULT NULL COMMENT '商品卖点',
  price bigint(20) DEFAULT NULL COMMENT '商品单价',
  num int(10) DEFAULT NULL COMMENT '库存数量',
  image varchar(500) DEFAULT NULL COMMENT '图片路径',
  `status` int(1) DEFAULT '1' COMMENT '商品状态  1:上架   2:下架   3:删除',
  priority int(10) DEFAULT NULL COMMENT '显示优先级',
  created_time datetime DEFAULT NULL COMMENT '创建时间',
  modified_time datetime DEFAULT NULL COMMENT '最后修改时间',
  created_user varchar(50) DEFAULT NULL COMMENT '创建人',
  modified_user varchar(50) DEFAULT NULL COMMENT '最后修改人',
  PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

插入数据

INSERT INTO t_product VALUES (10000001,238,'牛皮纸记事本','广博(GuangBo)10本装40张A5牛皮纸记事本子日记本办公软抄本GBR0731','经典回顾!超值特惠!'。。。)

🚀2.商品热销排行-创建实体类

创建com.cy.store.entity.Product类,并继承自BaseEntity类。在类中声明与数据表中对应的属性。

public class Product extends BaseEntity implements Serializable {
    private Integer id;
    private Integer categoryId;
    private String itemType;
    private String title;
    private String sellPoint;
    private Long price;
    private Integer num;
    private String image;
    private Integer status;
    private Integer priority;
......
}

🚀3.商品热销排行-持久层

✨3.1规划需要执行的SQL语句

查询热销商品列表的SQL语句。priority优先级:售卖的个数,售卖越多优先级越大。

select * from t_product where status=1
order by priority DESC limit 0,4

✨3.2接口和抽象方法 

在com.cy.store.mapper包下创建ProductMapper接口并在接口中添加查询热销商品findHotList()的方法。

    /**
     * 查询热销商品的前四名
     * @return 热销商品前四名的集合
     */
    List<Product> findHotList();

✨3.3配置映射

1.在main\resources\mapper文件夹下创建ProductMapper.xml文件,并在文件中配置findHotList()方法的映射。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.cy.store.mapper.ProductMapper">
    <resultMap id="ProductEntityMap" type="com.cy.store.entity.Product">
        <id property="id" column="id"/>
        <result column="category_id" property="categoryId"/>
        <result column="item_type" property="itemType"/>
        <result column="sell_point" property="sellPoint"/>
        <result column="created_user" property="createdUser"></result>
        <result column="created_time" property="createdTime"></result>
        <result column="modified_user" property="modifiedUser"></result>
        <result column="modified_time" property="modifiedTime"></result>
    </resultMap>
    <select id="findHotList">
        select * from t_product where status=1
        order by priority DESC limit 0,4
    </select>
</mapper>

 2.在com.cy.store.mapper包下创建ProductMapperTests测试类,并添加测试方法。

@SpringBootTest
public class ProductMapperTests {
    @Autowired
    private ProductMapper productMapper;

    @Test
    public void findHotList(){
        List<Product> list = productMapper.findHotList();
        System.out.println("count="+list.size());
        for(Product p : list){
            System.out.println(p);
        }

    }
}

🚀4.商品热销排行-业务层

✨4.1规划异常

无增删改,不会影响数据,无异常

 ✨4.2接口与抽象方法

创建com.cy.store.service.IProductService。

List<Product> findHotList();

✨4.3实现抽象方法

1.创建com.cy.store.service.impl.ProductServiceImpl类,并添加@Service注解;在类中声明持久层对象以及实现接口中的方法。这里在实际上页面中展示时只需要图片,标题,价格,还有隐藏的id,其余的设置为null就可以了。

@Service
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper productMapper;
    @Override
    public List<Product> findHotList() {
        List<Product> list = productMapper.findHotList();
        for(Product p : list){
            p.setPriority(null);
            p.setCreatedUser(null);
            p.setCreatedTime(null);
            p.setModifiedTime(null);
            p.setModifiedUser(null);
        }
        return list;
    }
}

🚀5.商品热销排行-控制层

✨5.1处理异常

无异常

✨5.2设计请求

1.设计用户的请求,并设计响应的方法。

请求路径:/products/hot_list

请求方式:GET

请求参数:无

响应结果:JsonResult<List<Product>>

是否拦截:否,需要将index.html和products/**添加到白名单

2.在LoginInterceptorConfigurer类中将index.html页面和products/**请求添加到白名单。

        patterns.add("/web/index.html");
        patterns.add("/products/**");

✨5.3处理请求

1.创建com.cy.store.controller.ProductController类中继承BaseController类,具体代码如下:

@RequestMapping("products")
@RestController
public class ProductController extends BaseController{
    @Autowired
    private IProductService productService;

    @RequestMapping("hot_list")
    public JsonResult<List<Product>> getHotList(){
        List<Product> data = productService.findHotList();
        return new JsonResult<>(OK,data);
    }
}

🚀6.商品热销排行-前端页面

1.在index.html页面给“热销排行”列表的div标签设置id属性值。

<div id="hot-list" class="panel-body panel-item">
。。。。。。
</div>

2.在index.html页面中body标签内部最后,添加展示热销排行商品的代码。

	<script>
		$(document).ready(function (){
			showHotList();
		});

		function showHotList(){
			$("#hot-list").empty();
			$.ajax({
				url: "/products/hot_list",
				type: "GET",
				dataType: "JSON",
				success: function(json) {
					var list = json.data;
					for (var i = 0; i < list.length; i++) {
						console.log(list[i].title);
						var html = '<div class="col-md-12">'
								+ '<div class="col-md-7 text-row-2"><a href="product.html?id=#{id}">#{title}</a></div>'
								+ '<div class="col-md-2">¥#{price}</div>'
								+ '<div class="col-md-3"><img src="..#{image}collect.png" class="img-responsive" /></div>'
								+ '</div>';

						html = html.replace(/#{id}/g, list[i].id);
						html = html.replace(/#{title}/g, list[i].title);
						html = html.replace(/#{price}/g, list[i].price);
						html = html.replace(/#{image}/g, list[i].image);

						$("#hot-list").append(html);
					}
				}
			});
		}
	</script>

🎯1.显示商品详情-持久层

✨1.1规划需要执行的SQL语句

根据商品id显示商品详情。

select * from t_product where id=?

✨1.2接口与抽象方法

在ProductMapper中添加抽象方法。

    /**
     * 根据商品id查询商品详情
     * @param id 商品id
     * @return 匹配的商品详情,如果没有匹配的商品返回null
     */
    Product findById(Integer id);

✨1.3配置SQL映射

1.在ProductMapper.xml文件中配置。

    <select id="findById" resultMap="ProductEntityMap">
        select * from t_product where id=#{id}
    </select>

2.在ProductMapperTests类中进行测试。

    @Test
    public void findById(){
        Product list = productMapper.findById(10000001);
        System.out.println(list);
    }

🎯2.显示商品详情-业务层

✨2.1规划异常

如果商品数据不存在,应该抛出ProductNotFoundException,需要创建com.cy.store.service.ex.ProductNotFoundException异常。

package com.cy.store.service.ex;

public class ProductNotFoundException extends ServiceException{
    public ProductNotFoundException() {
        super();
    }

    public ProductNotFoundException(String message) {
        super(message);
    }

    public ProductNotFoundException(String message, Throwable cause) {
        super(message, cause);
    }

    public ProductNotFoundException(Throwable cause) {
        super(cause);
    }

    protected ProductNotFoundException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
        super(message, cause, enableSuppression, writableStackTrace);
    }
}

✨2.2接口和抽象方法

在IProductService接口中编写抽象方法。

Product findById(Integer id);

✨2.3实现抽象方法

在ProductServiceImpl类中,实现接口中的抽象方法。

    @Override
    public Product findById(Integer id) {
        Product p = productMapper.findById(id);
        if(p == null){
            throw new ProductNotFoundException("尝试访问的商品数据不存在");
        }
        p.setPriority(null);
        p.setCreatedUser(null);
        p.setCreatedTime(null);
        p.setModifiedTime(null);
        p.setModifiedUser(null);
        return p;
    }
}

🎯3.显示商品详情-控制层

✨3.1处理异常

在BaseController类中的handleException中添加如下代码:

else if(e instanceof ProductNotFoundException) {
            result.setState(4006);
            result.setMessage("商品数据不存在的异常");
        }

✨3.2设计请求

设计用户提交的请求,并设计响应方式。

请求路径:/products/{id}/details

请求参数:@PathVariable("id"),Integer id

请求类型:GET

响应结果:JsonResult<Product>

✨3.3处理请求

1.在ProductController类中添加处理请求的getById()方法。

    @RequestMapping("{id}/details")
    public JsonResult<Product> getById(@PathVariable("id") Integer id){
        Product data = productService.findById(id);
        return new JsonResult<>(OK,data);
    }

2.完成后启动项目,直接访问http://localhost:8080/products/10000003/details

🎯4.显示商品详情-前端页面

1.检查product.html页面body标签内部的最后是否引入jquery-getUrlParam.js文件,如果引入无需重复引入。由于提交过来的id值在一个url地址上,如3.3的2中所示,所以这里就涉及到如何把这个url地址当中的id这一部分截取下来,截取下来是为了拼接到参数列表上发给后端,然后后端才可以完成查询操作。

<script type="text/javascript" src="../js/jquery-getUrlParam.js"></script>

2.在Product.html页面中body标签内部的最后添加获取当前商品详情的代码。

<script type="text/javascript">
			var id = $.getUrlParam("id");
			console.log("id=" + id);
			$(document).ready(function() {
				$.ajax({
					url: "/products/" + id + "/details",
					type: "GET",
					dataType: "JSON",
					success: function(json) {
						if (json.state == 200) {
							console.log("title=" + json.data.title);
							//<div></div>
							//有上面一个div,如果是html("hello"),那么html就会把hello在div容器里面呈现出来。
							//如果是html("<p></p>"),那么html就会把p标签追加到div内部作为它的一个子标签
							$("#product-title").html(json.data.title);
							$("#product-sell-point").html(json.data.sellPoint);
							$("#product-price").html(json.data.price);
							//总共有五张大图,一张小图
							for (var i = 1; i <= 5; i++) {
								$("#product-image-" + i + "-big").attr("src", ".." + json.data.image + i + "_big.png");
								$("#product-image-" + i).attr("src", ".." + json.data.image + i + ".jpg");
							}
						} else if (json.state == 4006) { // 商品数据不存在的异常
							location.href = "index.html";
						} else {
							alert("获取商品信息失败!" + json.message);
						}
					}
				});
			});
		</script>
评论 39
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值