用springboot,在表user(uid,uname,upwd)表commodity(cid,cname,cprice)表cart(cartid,cid,uid,cnum,cartprice,cartselected),表orders(oid,uid,cid,ocondition,oprice,ocount)的基础上实现购物车功能(加入购物车,加减商品数量,计算选中商品总价),加入购物车需要写入cart,提交订单要写入orders,计算总价需要根据选中商品数量和价格更新,代码包括html,entity,repository,service,controller
时间: 2023-09-24 16:11:47 浏览: 63
好的,下面是实现购物车功能的代码。
1. 实体类代码
User.java
```java
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer uid;
private String uname;
private String upwd;
// getter and setter
}
```
Commodity.java
```java
@Entity
@Table(name = "commodity")
public class Commodity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer cid;
private String cname;
private Float cprice;
// getter and setter
}
```
Cart.java
```java
@Entity
@Table(name = "cart")
public class Cart {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer cartid;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "uid")
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "cid")
private Commodity commodity;
private Integer cnum;
private Float cartprice;
private Boolean cartselected;
// getter and setter
}
```
Orders.java
```java
@Entity
@Table(name = "orders")
public class Orders {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer oid;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "uid")
private User user;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "cid")
private Commodity commodity;
private String ocondition;
private Float oprice;
private Integer ocount;
// getter and setter
}
```
2. Repository代码
UserRepository.java
```java
@Repository
public interface UserRepository extends JpaRepository<User, Integer> {
}
```
CommodityRepository.java
```java
@Repository
public interface CommodityRepository extends JpaRepository<Commodity, Integer> {
}
```
CartRepository.java
```java
@Repository
public interface CartRepository extends JpaRepository<Cart, Integer> {
List<Cart> findByUserAndCartselected(User user, Boolean cartselected);
}
```
OrdersRepository.java
```java
@Repository
public interface OrdersRepository extends JpaRepository<Orders, Integer> {
}
```
3. Service代码
UserService.java
```java
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
public User getUserById(Integer uid) {
return userRepository.findById(uid).orElse(null);
}
}
```
CommodityService.java
```java
@Service
public class CommodityService {
@Autowired
private CommodityRepository commodityRepository;
public Commodity getCommodityById(Integer cid) {
return commodityRepository.findById(cid).orElse(null);
}
}
```
CartService.java
```java
@Service
public class CartService {
@Autowired
private CartRepository cartRepository;
public void addToCart(User user, Commodity commodity, Integer cnum) {
Cart cart = cartRepository.findByUserAndCommodity(user, commodity);
if (cart == null) {
cart = new Cart();
cart.setUser(user);
cart.setCommodity(commodity);
cart.setCnum(cnum);
cart.setCartprice(commodity.getCprice() * cnum);
cart.setCartselected(true);
} else {
cart.setCnum(cart.getCnum() + cnum);
cart.setCartprice(cart.getCartprice() + commodity.getCprice() * cnum);
}
cartRepository.save(cart);
}
public List<Cart> getCartList(User user) {
return cartRepository.findByUserAndCartselected(user, true);
}
public void updateCart(Cart cart) {
cartRepository.save(cart);
}
public void deleteCart(Integer cartid) {
cartRepository.deleteById(cartid);
}
}
```
OrdersService.java
```java
@Service
public class OrdersService {
@Autowired
private OrdersRepository ordersRepository;
public void addOrder(User user, Commodity commodity, Integer ocount) {
Orders orders = new Orders();
orders.setUser(user);
orders.setCommodity(commodity);
orders.setOcondition("待发货");
orders.setOprice(commodity.getCprice() * ocount);
orders.setOcount(ocount);
ordersRepository.save(orders);
}
}
```
4. Controller代码
UserController.java
```java
@Controller
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/user/{uid}")
@ResponseBody
public User getUserById(@PathVariable Integer uid) {
return userService.getUserById(uid);
}
}
```
CommodityController.java
```java
@Controller
public class CommodityController {
@Autowired
private CommodityService commodityService;
@GetMapping("/commodity/{cid}")
@ResponseBody
public Commodity getCommodityById(@PathVariable Integer cid) {
return commodityService.getCommodityById(cid);
}
}
```
CartController.java
```java
@Controller
public class CartController {
@Autowired
private CartService cartService;
@Autowired
private UserService userService;
@Autowired
private CommodityService commodityService;
@PostMapping("/cart/add")
public String addToCart(Integer uid, Integer cid, Integer cnum) {
User user = userService.getUserById(uid);
Commodity commodity = commodityService.getCommodityById(cid);
cartService.addToCart(user, commodity, cnum);
return "redirect:/cart/list?uid=" + uid;
}
@GetMapping("/cart/list")
public String getCartList(Integer uid, Model model) {
User user = userService.getUserById(uid);
List<Cart> cartList = cartService.getCartList(user);
Float totalPrice = cartList.stream().map(Cart::getCartprice).reduce(0f, Float::sum);
model.addAttribute("cartList", cartList);
model.addAttribute("totalPrice", totalPrice);
return "cart";
}
@PostMapping("/cart/update")
@ResponseBody
public String updateCart(Integer cartid, Integer cnum) {
Cart cart = cartService.getCartById(cartid);
if (cart != null) {
cart.setCnum(cnum);
cart.setCartprice(cart.getCommodity().getCprice() * cnum);
cartService.updateCart(cart);
return "success";
}
return "fail";
}
@PostMapping("/cart/delete")
@ResponseBody
public String deleteCart(Integer cartid) {
cartService.deleteCart(cartid);
return "success";
}
}
```
OrdersController.java
```java
@Controller
public class OrdersController {
@Autowired
private OrdersService ordersService;
@Autowired
private UserService userService;
@Autowired
private CommodityService commodityService;
@PostMapping("/orders/add")
public String addOrder(Integer uid, Integer cid, Integer ocount) {
User user = userService.getUserById(uid);
Commodity commodity = commodityService.getCommodityById(cid);
ordersService.addOrder(user, commodity, ocount);
return "redirect:/cart/list?uid=" + uid;
}
}
```
5. 页面代码
cart.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>购物车</title>
<script src="https://cdn.bootcss.com/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<h1>购物车</h1>
<table border="1">
<thead>
<tr>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<form th:each="cart : ${cartList}">
<tr>
<td th:text="${cart.commodity.cname}"></td>
<td th:text="${cart.commodity.cprice}"></td>
<td>
<input type="number" name="cnum" th:value="${cart.cnum}" onchange="updateCart(this, [[${cart.cartid}]])">
</td>
<td th:text="${cart.cartprice}"></td>
<td>
<button type="button" onclick="deleteCart([[${cart.cartid}]])">删除</button>
</td>
</tr>
</form>
</tbody>
<tfoot>
<tr>
<td colspan="3">总计:</td>
<td th:text="${totalPrice}"></td>
<td><button type="button" onclick="submitOrders([[${uid}]])">提交订单</button></td>
</tr>
</tfoot>
</table>
<script>
function updateCart(obj, cartid) {
var cnum = $(obj).val();
$.ajax({
url: "/cart/update",
type: "post",
dataType: "text",
data: {
cartid: cartid,
cnum: cnum
},
success: function (data) {
if (data == "success") {
location.reload();
} else {
alert("更新购物车失败");
}
},
error: function () {
alert("更新购物车失败");
}
});
}
function deleteCart(cartid) {
$.ajax({
url: "/cart/delete",
type: "post",
dataType: "text",
data: {
cartid: cartid
},
success: function (data) {
if (data == "success") {
location.reload();
} else {
alert("删除购物车失败");
}
},
error: function () {
alert("删除购物车失败");
}
});
}
function submitOrders(uid) {
var cartList = [];
$('input[name="cartid"]:checked').each(function () {
cartList.push($(this).val());
});
if (cartList.length == 0) {
alert("请选择要购买的商品");
return;
}
$.ajax({
url: "/orders/add",
type: "post",
dataType: "text",
data: {
uid: uid,
cid: cartList[0],
ocount: cartList.length
},
success: function (data) {
if (data == "success") {
location.href = "/orders/list?uid=" + uid;
} else {
alert("提交订单失败");
}
},
error: function () {
alert("提交订单失败");
}
});
}
</script>
</body>
</html>
```
orders.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>订单列表</title>
</head>
<body>
<h1>订单列表</h1>
<table border="1">
<thead>
<tr>
<th>订单号</th>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>总价</th>
<th>状态</th>
</tr>
</thead>
<tbody>
<form th:each="orders : ${ordersList}">
<tr>
<td th:text="${orders.oid}"></td>
<td th:text="${orders.commodity.cname}"></td>
<td th:text="${orders.commodity.cprice}"></td>
<td th:text="${orders.ocount}"></td>
<td th:text="${orders.oprice}"></td>
<td th:text="${orders.ocondition}"></td>
</tr>
</form>
</tbody>
</table>
</body>
</html>
```
至此,基于Spring Boot实现购物车功能的代码就介绍完了。
阅读全文