使用SpringBoot开发简易版商城系统

项目结构

在这里插入图片描述

商城首页

在这里插入图片描述

github项目地址

https://github.com/yangzc23/yangzc

依赖配置pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.cskfz</groupId>
        <artifactId>yangzc</artifactId>
        <version>1.0-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cskfz</groupId>
    <artifactId>tmall</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>tmall</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <mysql.version>5.1.41</mysql.version>
        <springboot.version>2.2.1.RELEASE</springboot.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>${springboot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <version>${springboot.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
            <version>${springboot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <version>${springboot.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <version>${springboot.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

SpringBoot配置application.properties

server.port = 8080
server.servlet.context-path = /tmall

spring.datasource.url = jdbc:mysql://localhost:3306/tmall?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=utf8
spring.datasource.username = root
spring.datasource.password = 123456
spring.datasource.driverClassName = com.mysql.jdbc.Driver
# Specify the DBMS
spring.jpa.database = MYSQL
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# stripped before adding them to the entity manager)
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Hibernate配置HibernateConfig.java

package com.cskfz.tmall.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternUtils;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;

import javax.sql.DataSource;
import java.io.IOException;
import java.util.Properties;

/**
 * @Author: yangzc
 * @Description:
 * @Date: Created on 16:04 2019/11/16
 * @Modified By:
 */
@Configuration
public class HibernateConfig {

    @Autowired
    private DataSource dataSource;


    @Autowired
    private ResourceLoader rl;

    @Bean
    public LocalSessionFactoryBean sessionFactoryBean() {
        LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);
        sessionFactoryBean.setPackagesToScan("com.cskfz.tmall.entity");//dao和entity的公共包
        sessionFactoryBean.setMappingLocations(loadResources());
        //sessionFactoryBean.setMappingResources("/sqlMapperXml/TItem.hbm.xml","/sqlMapperXml/TOrder.hbm.xml","/sqlMapperXml/TProduct.hbm.xml","/sqlMapperXml/TUser.hbm.xml");
        Properties properties = new Properties();
        properties.setProperty("hibernate.dialect","org.hibernate.dialect.MySQL5Dialect");
        properties.setProperty("hibernate.show_sql","true");
        properties.setProperty("hibernate.hbm2ddl.auto","update");
        sessionFactoryBean.setHibernateProperties(properties);
        return sessionFactoryBean;
    }

    public Resource[] loadResources() {
        Resource[] resources = null;
        try {
            resources = ResourcePatternUtils.getResourcePatternResolver(rl).getResources("classpath:/sqlMapperXml/*.hbm.xml");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return resources;
    }
}

Controller代码

package com.cskfz.tmall.controller;

import com.cskfz.tmall.dao.TProductHome;
import com.cskfz.tmall.entity.TProduct;
import com.cskfz.tmall.pojo.ActionResult;
import com.cskfz.tmall.pojo.ProductVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * @Author: yangzc
 * @Description:
 * @Date: Created on 16:04 2019/11/16
 * @Modified By:
 */
@Controller
@RequestMapping("/")
public class MyController {

    @Autowired
    private TProductHome productDao;


    @GetMapping("/index")
    public String homePage() {
        return "index";
    }

    @GetMapping("/cart")
    public String cartPage() {
        return "cart";
    }

    /**
     * 获取商品列表
     * @param map
     * @return
     */
    @RequestMapping(value = "/portal/list",method = RequestMethod.POST)
    @ResponseBody
    public ActionResult getProducts(@RequestBody Map<String,String> map) {
        //int rows = Integer.parseInt(req.getParameter("rows"));
        int rows = Integer.parseInt(map.get("rows"));
        //
        //int page = Integer.parseInt(req.getParameter("page"));
        int page = Integer.parseInt(map.get("page"));
        int begin = (page-1)*rows;
        int total = productDao.getTotal();
        List<TProduct> list = productDao.findByExample(begin, rows);
        List<ProductVO> list2 = new ArrayList<ProductVO>();
        Map<String,Object> data = new HashMap<String,Object>();
        for(TProduct p:list) {
            ProductVO pvo = new ProductVO();
            pvo.setId(p.getId());
            pvo.setName(p.getName());
            pvo.setImageUrl(p.getImageUrl());
            pvo.setPrice(p.getPrice());
            pvo.setStock(p.getStock());
            pvo.setQuantity(1);
            list2.add(pvo);
        }
        data.put("total", total);
        data.put("rows", list2);
        return ActionResult.ok(data);
    }

}

dao代码

package com.cskfz.tmall.dao;
// default package
// Generated 2019-9-27 10:53:04 by Hibernate Tools 4.3.5.Final

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.cskfz.tmall.entity.TProduct;



/**
 * Home object for domain model class TProduct.
 * @see .TProduct
 * @author Hibernate Tools
 */
@Repository
@Transactional
public class TProductHome {

	private static final Log log = LogFactory.getLog(TProductHome.class);

	@Autowired
	private SessionFactory sessionFactory;

	public void persist(TProduct transientInstance) {
		log.debug("persisting TProduct instance");
		try {
			sessionFactory.getCurrentSession().persist(transientInstance);
			log.debug("persist successful");
		} catch (RuntimeException re) {
			log.error("persist failed", re);
			throw re;
		}
	}

	public void attachDirty(TProduct instance) {
		log.debug("attaching dirty TProduct instance");
		try {
			sessionFactory.getCurrentSession().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(TProduct instance) {
		log.debug("attaching clean TProduct instance");
		try {
			sessionFactory.getCurrentSession().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void delete(TProduct persistentInstance) {
		log.debug("deleting TProduct instance");
		try {
			sessionFactory.getCurrentSession().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public TProduct merge(TProduct detachedInstance) {
		log.debug("merging TProduct instance");
		try {
			TProduct result = (TProduct) sessionFactory.getCurrentSession().merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public TProduct findById(int id) {
		log.debug("getting TProduct instance with id: " + id);
		try {
			TProduct instance = (TProduct) sessionFactory.getCurrentSession().get("com.cskfz.tmall.entity.TProduct", id);
			if (instance == null) {
				log.debug("get successful, no instance found");
			} else {
				log.debug("get successful, instance found");
			}
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List findByExample(TProduct instance) {
		log.debug("finding TProduct instance by example");
		try {
			List results = sessionFactory.getCurrentSession().createCriteria("com.cskfz.tmall.entity.TProduct").add(Example.create(instance))
					.list();
			log.debug("find by example successful, result size: " + results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}
	
	public List findByExample(int begin, int rows) {
		log.debug("finding TUser instance by example");
		try {
			Criteria criteria = sessionFactory.getCurrentSession().createCriteria("com.cskfz.tmall.entity.TProduct");
			criteria.setFirstResult(begin);
			criteria.setMaxResults(rows);
			List results = criteria.list();	
			log.debug("find by example successful, result size: " + results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}
	
	public int getTotal() {
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria("com.cskfz.tmall.entity.TProduct");
		//计算总数
		criteria.setProjection(Projections.rowCount());
		return ((Long)criteria.uniqueResult()).intValue();
	}
	
}

实体类Product

package com.cskfz.tmall.entity;
// default package
// Generated 2019-9-27 10:33:55 by Hibernate Tools 4.3.5.Final

import java.util.HashSet;
import java.util.Set;



/**
 * TProduct generated by hbm2java
 */
public class TProduct implements java.io.Serializable {

	private int id;
	private String name;
	private Float price;
	private Integer exchangeCredit;
	private Integer exchangeCountLimit;
	private Integer stock;
	private Boolean exchangeFlag;
	private String imageUrl;
	private String desc;
	
	private Set TItems = new HashSet(0);

	public TProduct() {
	}

	public TProduct(int id) {
		this.id = id;
	}

	public TProduct(int id, String name, Float price, Integer exchangeCredit, Integer exchangeCountLimit, Integer stock,
			Boolean exchangeFlag, String imageUrl, String desc, Set TItems) {
		this.id = id;
		this.name = name;
		this.price = price;
		this.exchangeCredit = exchangeCredit;
		this.exchangeCountLimit = exchangeCountLimit;
		this.stock = stock;
		this.exchangeFlag = exchangeFlag;
		this.imageUrl = imageUrl;
		this.desc = desc;
		this.TItems = TItems;
	}

	public int getId() {
		return this.id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Float getPrice() {
		return this.price;
	}

	public void setPrice(Float price) {
		this.price = price;
	}

	public Integer getExchangeCredit() {
		return this.exchangeCredit;
	}

	public void setExchangeCredit(Integer exchangeCredit) {
		this.exchangeCredit = exchangeCredit;
	}

	public Integer getExchangeCountLimit() {
		return this.exchangeCountLimit;
	}

	public void setExchangeCountLimit(Integer exchangeCountLimit) {
		this.exchangeCountLimit = exchangeCountLimit;
	}

	public Integer getStock() {
		return this.stock;
	}

	public void setStock(Integer stock) {
		this.stock = stock;
	}

	public Boolean getExchangeFlag() {
		return this.exchangeFlag;
	}

	public void setExchangeFlag(Boolean exchangeFlag) {
		this.exchangeFlag = exchangeFlag;
	}

	public String getImageUrl() {
		return imageUrl;
	}

	public void setImageUrl(String imageUrl) {
		this.imageUrl = imageUrl;
	}	
	
	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}

	public Set getTItems() {
		return this.TItems;
	}

	public void setTItems(Set TItems) {
		this.TItems = TItems;
	}

}

vo类

package com.cskfz.tmall.pojo;



/**
 * TProduct generated by hbm2java
 */
public class ProductVO implements java.io.Serializable {

	private int id;
	private String name;
	private Float price;
	private Integer exchangeCredit;
	private Integer exchangeCountLimit;
	private Integer stock;
	private Boolean exchangeFlag;
	private String imageUrl;
	private String desc;
	private Integer quantity;
	
	public ProductVO() {
	}

	public ProductVO(int id) {
		this.id = id;
	}

	public ProductVO(int id, String name, Float price, Integer exchangeCredit, Integer exchangeCountLimit, Integer stock,
			Boolean exchangeFlag, String imageUrl, String desc, Integer quantity) {
		this.id = id;
		this.name = name;
		this.price = price;
		this.exchangeCredit = exchangeCredit;
		this.exchangeCountLimit = exchangeCountLimit;
		this.stock = stock;
		this.exchangeFlag = exchangeFlag;
		this.imageUrl = imageUrl;
		this.desc = desc;
		this.quantity = quantity;
	}

	public int getId() {
		return this.id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Float getPrice() {
		return this.price;
	}

	public void setPrice(Float price) {
		this.price = price;
	}

	public Integer getExchangeCredit() {
		return this.exchangeCredit;
	}

	public void setExchangeCredit(Integer exchangeCredit) {
		this.exchangeCredit = exchangeCredit;
	}

	public Integer getExchangeCountLimit() {
		return this.exchangeCountLimit;
	}

	public void setExchangeCountLimit(Integer exchangeCountLimit) {
		this.exchangeCountLimit = exchangeCountLimit;
	}

	public Integer getStock() {
		return this.stock;
	}

	public void setStock(Integer stock) {
		this.stock = stock;
	}

	public Boolean getExchangeFlag() {
		return this.exchangeFlag;
	}

	public void setExchangeFlag(Boolean exchangeFlag) {
		this.exchangeFlag = exchangeFlag;
	}

	public String getImageUrl() {
		return imageUrl;
	}

	public void setImageUrl(String imageUrl) {
		this.imageUrl = imageUrl;
	}	
	
	public String getDesc() {
		return desc;
	}

	public void setDesc(String desc) {
		this.desc = desc;
	}	
	
	public Integer getQuantity() {
		return quantity;
	}

	public void setQuantity(Integer quantity) {
		this.quantity = quantity;
	}

}

自定义响应结构

package com.cskfz.tmall.pojo;

import java.io.Serializable;
import java.util.List;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 自定义响应结构
 */
public class ActionResult implements Serializable{

	private static final long serialVersionUID = 1L;

	// 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    // 响应业务状态
    private Integer status;

    // 响应消息
    private String msg;

    // 响应中的数据
    private Object data;

    public static ActionResult build(Integer status, String msg, Object data) {
        return new ActionResult(status, msg, data);
    }

    public static ActionResult ok(Object data) {
        return new ActionResult(data);
    }

    public static ActionResult ok() {
        return new ActionResult(null);
    }
    
    public static ActionResult fail(String msg) {
        return new ActionResult(500,msg,null);
    }    

    public ActionResult() {

    }

    public static ActionResult build(Integer status, String msg) {
        return new ActionResult(status, msg, null);
    }

    public ActionResult(Integer status, String msg, Object data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
    }

    public ActionResult(Object data) {
        this.status = 200;
        this.msg = "OK";
        this.data = data;
    }

//    public Boolean isOK() {
//        return this.status == 200;
//    }

    public Integer getStatus() {
        return status;
    }

    public void setStatus(Integer status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    /**
     * 将json结果集转化为ActionResult对象
     * 
     * @param jsonData json数据
     * @param clazz ActionResult中的object类型
     * @return
     */
    public static ActionResult formatToPojo(String jsonData, Class<?> clazz) {
        try {
            if (clazz == null) {
                return MAPPER.readValue(jsonData, ActionResult.class);
            }
            JsonNode jsonNode = MAPPER.readTree(jsonData);
            JsonNode data = jsonNode.get("data");
            Object obj = null;
            if (clazz != null) {
                if (data.isObject()) {
                    obj = MAPPER.readValue(data.traverse(), clazz);
                } else if (data.isTextual()) {
                    obj = MAPPER.readValue(data.asText(), clazz);
                }
            }
            return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 没有object对象的转化
     * 
     * @param json
     * @return
     */
    public static ActionResult format(String json) {
        try {
            return MAPPER.readValue(json, ActionResult.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Object是集合转化
     * 
     * @param jsonData json数据
     * @param clazz 集合中的类型
     * @return
     */
    public static ActionResult formatToList(String jsonData, Class<?> clazz) {
        try {
            JsonNode jsonNode = MAPPER.readTree(jsonData);
            JsonNode data = jsonNode.get("data");
            Object obj = null;
            if (data.isArray() && data.size() > 0) {
                obj = MAPPER.readValue(data.traverse(),
                        MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
            }
            return build(jsonNode.get("status").intValue(), jsonNode.get("msg").asText(), obj);
        } catch (Exception e) {
            return null;
        }
    }

}

主类

package com.cskfz.tmall;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@EnableTransactionManagement
@SpringBootApplication
public class TmallApplication {

    public static void main(String[] args) {
        SpringApplication.run(TmallApplication.class, args);
    }

}

数据表映射文件TProduct.hbm.xml

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 2019-9-27 10:33:55 by Hibernate Tools 4.3.5.Final -->
<hibernate-mapping>
    <class name="com.cskfz.tmall.entity.TProduct" table="t_product" catalog="tmall" optimistic-lock="version">
        <id name="id" type="int">
            <column name="id" />
            <generator class="assigned" />
        </id>
        <property name="name" type="string">
            <column name="name" length="50" />
        </property>
        <property name="price" type="java.lang.Float">
            <column name="price" precision="10" />
        </property>
        <property name="exchangeCredit" type="java.lang.Integer">
            <column name="exchange_credit" />
        </property>
        <property name="exchangeCountLimit" type="java.lang.Integer">
            <column name="exchange_count_limit" />
        </property>
        <property name="stock" type="java.lang.Integer">
            <column name="stock" />
        </property>
        <property name="exchangeFlag" type="java.lang.Boolean">
            <column name="exchange_flag" />
        </property>
        <property name="imageUrl" type="java.lang.String">
            <column name="img_url" />
        </property>        
        <property name="desc" type="java.lang.String">
            <column name="description" />
        </property>
    </class>
</hibernate-mapping>

首页html代码

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>欢迎来到天猫商城</title>
<link rel="shortcut icon" th:href="@{/favicon.ico}">
<link rel="bookmark" th:href="@{/favicon.ico}" type="image/x-icon" />
<link type="text/css" rel="stylesheet" th:href="@{/css/bootstrap.css}">
<link type="text/css" rel="stylesheet" th:href="@{/css/bootstrap-table.css}">
<script src="js/jquery.js"></script>
<script src="js/bootstrap.js" type="text/javascript" charset="utf-8"></script>
<script src="js/bootstrap-table.js"></script>
<script src="js/bootstrap-table-zh-CN.js"></script>
<script src="js/tmall.js"></script>
<script type="text/javascript">	
	$(function(){
		//console.log('test....');
		initMainTable();
		$('#usrname').text(sessionStorage.getItem('user'));
		$('#points').text(sessionStorage.getItem('credit'));
		var str = sessionStorage.getItem('cart');
		var cart;
		if(str!=null){
			cart = JSON.parse(str);
			$("#quantity").text(cart.length);
			if(cart.length>0){
				$("#quantity").addClass("badge");
				$("#quantity").css("background-color","red");
			}
		}
	});
	

</script>
</head>
<body>
<ul class="nav nav-pills">
  <li role="presentation" class="active" ><a href="#">首页</a></li>
  <li role="presentation"><a href="orderDetail">我的淘宝</a></li>
  <li role="presentation"><a href="cart">购物车 <span id="quantity">0</span></a></li>
  <li role="presentation"><a href="#">您好,<span id="usrname"></span></a></li>
  <li role="presentation"><a href="#">积分<span id="points"></span></a></li>
  <li role="presentation"><a href="javascript:;" onclick="logout();">退出</a></li>
</ul>
<div>
<table id="grid" class="table"></table>
</div>
</body>
</html>

首页js代码

var $table;	
var rows = 3;

function initMainTable() {	//初始化bootstrap-table的内容
    //记录页面bootstrap-table全局变量$table,方便应用
    var queryUrl = 'portal/list';
    $table = $('#grid').bootstrapTable({
        url: queryUrl,                      //请求后台的URL(*)
        method: 'POST',                      //请求方式(*)
        striped: true,                      //是否显示行间隔色
        cache: false,                       //是否使用缓存,默认为true,所以一般情况下需要设置一下这个属性(*)
        pagination: true,                   //是否显示分页(*)
        sortable: true,                     //是否启用排序
        sortOrder: "asc",                   //排序方式
        sidePagination: "server",           //分页方式:client客户端分页,server服务端分页(*)
        pageNumber: 1,                      //初始化加载第一页,默认第一页,并记录
        pageSize: rows,                     //每页的记录行数(*)
        pageList: [10, 25, 50, 100],        //可供选择的每页的行数(*)
        search: false,                      //是否显示表格搜索
        strictSearch: true,
        showColumns: true,                  //是否显示所有的列(选择显示的列)
        showRefresh: true,                  //是否显示刷新按钮
        minimumCountColumns: 2,             //最少允许的列数
        clickToSelect: true,                //是否启用点击选中行
        //height: 500,                      //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度
        uniqueId: "id",                     //每一行的唯一标识,一般为主键列
        showToggle: true,                   //是否显示详细视图和列表视图的切换按钮
        cardView: false,                    //是否显示详细视图
        detailView: false,                  //是否显示父子表
        //得到查询的参数
        queryParams : function (params) {
            //这里的键的名字和控制器的变量名必须一直,这边改动,控制器也需要改成一样的
            var temp = {   
                rows: params.limit,                         //页面大小
                page: (params.offset / params.limit) + 1,   //页码
                sort: params.sort,      //排序列名  
                sortOrder: params.order //排位命令(desc,asc) 
            };
            return JSON.stringify(temp);
        },
        columns: [{
            field: 'id',
            title: '编号',
            visible: false,
            sortable: true
        }, {
            field: 'imageUrl',
            title: '实物图片',
            width: 120,
            formatter: imageFormatter
        }, {
            field: 'name',
            title: '商品名称',
            sortable: true
        }, {
            field: 'price',
            title: '单价',
            sortable: true,      
            formatter: priceFormatter
        }, {
            field: 'stock',
            title: '库存',
        }, {
            field: 'quantity',
            title: '购买数量',
            formatter: quantityFormatter
        }, {
            field:'id',
            title: '操作',
            width: 150,
            align: 'center',
            valign: 'middle',
            formatter: actionFormatter
        }, ],
        onLoadSuccess: function () {
        },
        onLoadError: function () {
            alert("数据加载失败!");
        },
        responseHandler: responseHandler,
    });
};

function actionFormatter(value, row, index) {	//操作栏的格式化
    var id = value;
    var result = "<button type=\"button\" class=\"btn btn-primary\" οnclick=\"add("+id+",this);\"><span class=\"glyphicon glyphicon-shopping-cart\" aria-hidden=\"true\"></span> 加入购物车</button>";
    return result;
}

/**
 * 获取返回的数据的时候做相应处理,让bootstrap table认识我们的返回格式
 * @param {Object} res
 */
function responseHandler(res) {
	 return {
		 "rows": res.data.rows, // 具体每一个bean的列表
		 "total": res.data.total // 总共有多少条返回数据
	 }
}

function quantityFormatter(value, row, index) {	//
    var result = "<input type='text' size='3' value='1' />";
    return result;
}

function priceFormatter(value, row, index) {	//
    var result = '¥'+value.toFixed(2);
    return result;
}

function imageFormatter(value, row, index){
	var result = "<img src=\""+value+"\">";
	return result;
}

function add(id, e){
	var str = sessionStorage.getItem('cart');
	//alert(str);
	var cart;
	if(str == null||str == undefined){
		cart = [];
	} else {
		cart = JSON.parse(str);
	}
	$td = $(e).parent().prev();
	var nodes = $td.children();
	var n = parseInt(nodes[0].value);
	var row = $table.bootstrapTable('getRowByUniqueId', id);
	//alert(JSON.stringify(row));
	var item = row;
	item.quantity = n;
	cart.push(item);
	alert(JSON.stringify(cart));
	sessionStorage.setItem('cart',JSON.stringify(cart));
	$("#quantity").addClass("badge");
	$("#quantity").css("background-color","red");
	//$("#quantity").addClass("bg-info");
	$("#quantity").text(cart.length);
	//console.log('test.....');
	//var cart = sessionStorage.getItem('cart');
	//cart.push(row);
	//alert(cart[0]);
}

function logout(){
    $.ajax({
    	//几个参数需要注意一下
        type: "get",//方法类型
        dataType: "json",//预期服务器返回的数据类型
        url: "portal/logout" ,//url
        success: function (data) {
            //console.log(data);//打印服务端返回的数据(调试用)
            if (data.status == 200) {
            	document.location = "login.html";
            }
        },
        error : function() {
            alert("异常!");
        }
    });
}

/*
 * 获取到Url里面的参数
 */
function getUrlParam(name){
	   var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
	   var r = window.location.search.substr(1).match(reg);
	   if (r != null) 
		   return unescape(r[2]); 
	   return null;
}

参考资料

[01] SpringBoot2.x与Hibernate那点事儿
[02] Hibernate5.2版本之后 createCriteria()方法过时的替换方式
[03] spring-boot工程中,jpa下hibernate的ddl-auto的各种属性
[04] springboot整合hibernate,根据数据库自动生成映射文件
[05] SpringBoot 属性配置文件详解
[06] springboot中hibernate配置sessionFactory访问数据库
[07] Hibernate中的show_sql和Spring中的hibernate.show_sql的区别
[08] Hibernate配制项之hibernate.show_sql, hibernate.show_sql和hibernate.use_sql_comments
[09] springboot 获取hibernate 的 SessionFactory
[10] springBoot+Hibernate多数据源配置与使用
[11] idea上Springboot项目导入mybatis依赖显示unknown是怎么回事?
[12] springboot配置hibernate双向一对多时出现json死循环

微信扫一扫关注公众号
image.png
点击链接加入群聊

https://jq.qq.com/?_wv=1027&k=5eVEhfN
软件测试学习交流QQ群号:511619105

  • 5
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值