你在某个在线商城上购物,浏览商品、将商品添加到购物车、最后下订单。这一系列操作背后,Java Web应用正在高效地处理用户请求、存储数据、生成订单等。在电子商务中,在线商城是一个重要的商业模式。
随着互联网的发展,越来越多的企业选择通过在线商城进行产品销售。Java作为一种广泛使用的编程语言,因其跨平台性、稳定性和强大的生态系统而被广泛应用于Web开发中。
一、项目结构
在本项目中,我们将实现一个简单的在线商城,主要包括以下模块:
-
商品展示:用户可以查看商品列表及详情。
-
购物车:用户可以将商品添加到购物车,修改商品数量。
-
订单处理:用户可以生成订单并查看订单状态。
项目技术栈
-
前端:HTML, CSS, JavaScript
-
后端:Java (Spring Boot)
-
数据库:MySQL
-
其他:Maven, Thymeleaf (模板引擎)
二、理论知识
1. Spring Boot简介
Spring Boot是一个快速开发框架,可以帮助开发者快速构建基于Spring的应用程序。它提供了许多开箱即用的功能,如自动配置、嵌入式服务器等,减少了开发的复杂性。
2. MVC架构
MVC(Model-View-Controller)是一种设计模式,用于分离应用程序的关注点。它将应用程序分为三部分:
-
Model:数据模型,负责业务逻辑和数据处理。
-
View:用户界面,负责展示数据。
-
Controller:控制器,处理用户输入,调用Model和View。
3. RESTful API
REST(Representational State Transfer)是一种软件架构风格,常用于Web服务。RESTful API通过HTTP协议提供资源的创建、读取、更新和删除(CRUD)操作。
三、具体实现
1. 创建Spring Boot项目
使用Spring Initializr创建一个新的Spring Boot项目,选择以下依赖:
-
Spring Web
-
Spring Data JPA
-
MySQL Driver
-
Thymeleaf
2. 数据库设计
我们需要设计三个主要的表:products
(商品表)、cart
(购物车表)、orders
(订单表)。
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
description TEXT,
stock INT NOT NULL
);
CREATE TABLE cart (
id INT AUTO_INCREMENT PRIMARY KEY,
product_id INT NOT NULL,
quantity INT NOT NULL,
FOREIGN KEY (product_id) REFERENCES products(id)
);
CREATE TABLE orders (
id INT AUTO_INCREMENT PRIMARY KEY,
total DECIMAL(10, 2) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
3. 商品展示功能
3.1 创建商品实体类
@Entity
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private BigDecimal price;
private String description;
private int stock;
// Getters and Setters
}
3.2 创建商品Repository
public interface ProductRepository extends JpaRepository<Product, Long> {
List<Product> findAll();
}
3.3 创建商品Controller
@Controller
@RequestMapping("/products")
public class ProductController {
@Autowired
private ProductRepository productRepository;
@GetMapping
public String listProducts(Model model) {
List<Product> products = productRepository.findAll();
model.addAttribute("products", products);
return "product/list"; // 返回商品列表视图
}
}
3.4 创建商品列表视图
在src/main/resources/templates/product/list.html
中创建商品列表视图:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>商品列表</title>
</head>
<body>
<h1>商品列表</h1>
<table>
<tr>
<th>商品名称</th>
<th>价格</th>
<th>描述</th>
<th>操作</th>
</tr>
<tr th:each="product : ${products}">
<td th:text="${product.name}"></td>
<td th:text="${product.price}"></td>
<td th:text="${product.description}"></td>
<td>
<a th:href="@{/cart/add(productId=${product.id})}">添加到购物车</a>
</td>
</tr>
</table>
</body>
</html>
4. 购物车功能
4.1 创建购物车实体类
@Entity
public class CartItem {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long productId;
private int quantity;
// Getters and Setters
}
4.2 创建购物车Controller
@Controller
@RequestMapping("/cart")
public class CartController {
private List<CartItem> cartItems = new ArrayList<>();
@GetMapping
public String viewCart(Model model) {
model.addAttribute("cartItems", cartItems);
return "cart/view"; // 返回购物车视图
}
@GetMapping("/add")
public String addToCart(@RequestParam Long productId) {
// 查找购物车中是否已存在该商品
Optional<CartItem> existingItem = cartItems.stream()
.filter(item -> item.getProductId().equals(productId))
.findFirst();
if (existingItem.isPresent()) {
existingItem.get().setQuantity(existingItem.get().getQuantity() + 1);
} else {
CartItem newItem = new CartItem();
newItem.setProductId(productId);
newItem.setQuantity(1);
cartItems.add(newItem);
}
return "redirect:/cart"; // 重定向到购物车视图
}
}
4.3 创建购物车视图
在src/main/resources/templates/cart/view.html
中创建购物车视图:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>购物车</title>
</head>
<body>
<h1>购物车</h1>
<table>
<tr>
<th>商品ID</th>
<th>数量</th>
</tr>
<tr th:each="item : ${cartItems}">
<td th:text="${item.productId}"></td>
<td th:text="${item.quantity}"></td>
</tr>
</table>
</body>
</html>
5. 订单处理功能
5.1 创建订单实体类
@Entity
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private BigDecimal total;
private LocalDateTime createdAt;
// Getters and Setters
}
5.2 创建订单Controller
@Controller
@RequestMapping("/orders")
public class OrderController {
@Autowired
private OrderRepository orderRepository;
@PostMapping("/create")
public String createOrder(@RequestParam BigDecimal total) {
Order order = new Order();
order.setTotal(total);
order.setCreatedAt(LocalDateTime.now());
orderRepository.save(order);
return "redirect:/orders"; // 重定向到订单列表视图
}
}
5.3 创建订单Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findAll();
}
5.4 创建订单列表视图
在src/main/resources/templates/orders/list.html
中创建订单列表视图:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>订单列表</title>
</head>
<body>
<h1>订单列表</h1>
<table>
<tr>
<th>订单ID</th>
<th>总金额</th>
<th>创建时间</th>
</tr>
<tr th:each="order : ${orders}">
<td th:text="${order.id}"></td>
<td th:text="${order.total}"></td>
<td th:text="${order.createdAt}"></td>
</tr>
</table>
</body>
</html>