编写一个基于MVC的网络点餐系统代码
时间: 2024-05-13 11:17:36 浏览: 135
基于MVC模式的订餐系统的设计与实现
这是一个简单的基于MVC的网络点餐系统代码示例,使用Java语言和Spring框架实现:
Model部分:
```
public class MenuItem {
private int id;
private String name;
private double price;
// getters and setters
}
public class OrderItem {
private MenuItem menuItem;
private int quantity;
// getters and setters
}
public class Order {
private List<OrderItem> orderItems;
private double totalPrice;
// getters and setters
}
```
View部分:
```
// 菜单页面
<table>
<tr>
<th>ID</th>
<th>名称</th>
<th>价格</th>
<th>数量</th>
<th>添加</th>
</tr>
<c:forEach items="${menuItems}" var="menuItem">
<tr>
<td>${menuItem.id}</td>
<td>${menuItem.name}</td>
<td>${menuItem.price}</td>
<td><input type="number" name="quantity_${menuItem.id}" value="0"></td>
<td><button onclick="addToCart(${menuItem.id})">添加到购物车</button></td>
</tr>
</c:forEach>
</table>
// 购物车页面
<table>
<tr>
<th>ID</th>
<th>名称</th>
<th>数量</th>
<th>单价</th>
<th>小计</th>
</tr>
<c:forEach items="${orderItems}" var="orderItem">
<tr>
<td>${orderItem.menuItem.id}</td>
<td>${orderItem.menuItem.name}</td>
<td>${orderItem.quantity}</td>
<td>${orderItem.menuItem.price}</td>
<td>${orderItem.menuItem.price * orderItem.quantity}</td>
</tr>
</c:forEach>
<tr>
<td colspan="4">总价</td>
<td>${totalPrice}</td>
</tr>
<tr>
<td colspan="5"><button onclick="submitOrder()">提交订单</button></td>
</tr>
</table>
```
Controller部分:
```
@Controller
@RequestMapping("/menu")
public class MenuController {
@Autowired
private MenuService menuService;
@GetMapping("")
public String showMenu(Model model) {
List<MenuItem> menuItems = menuService.getAllMenuItems();
model.addAttribute("menuItems", menuItems);
return "menu";
}
}
@Controller
@RequestMapping("/cart")
public class CartController {
@Autowired
private OrderService orderService;
@GetMapping("")
public String showCart(Model model) {
Order order = orderService.getCurrentOrder();
model.addAttribute("orderItems", order.getOrderItems());
model.addAttribute("totalPrice", order.getTotalPrice());
return "cart";
}
@PostMapping("/add-to-cart")
public String addToCart(@RequestParam int menuItemId, @RequestParam int quantity) {
orderService.addToCart(menuItemId, quantity);
return "redirect:/cart";
}
@PostMapping("/submit-order")
public String submitOrder() {
orderService.submitOrder();
return "redirect:/menu";
}
}
```
Service部分:
```
@Service
public class MenuService {
public List<MenuItem> getAllMenuItems() {
// 获取所有菜单项
}
}
@Service
@SessionScope
public class OrderService {
private Order currentOrder;
public Order getCurrentOrder() {
if (currentOrder == null) {
currentOrder = new Order();
}
return currentOrder;
}
public void addToCart(int menuItemId, int quantity) {
MenuItem menuItem = getMenuService().getMenuItemById(menuItemId);
OrderItem orderItem = new OrderItem(menuItem, quantity);
getCurrentOrder().addOrderItem(orderItem);
}
public void submitOrder() {
// 将当前订单提交到数据库中,并清空当前订单
}
}
```
这只是一个简单的示例,实际的网络点餐系统可能需要更复杂的逻辑和功能。
阅读全文