用java web 写一个点餐系统的代码
时间: 2024-05-04 19:16:35 浏览: 171
好的,我可以回答您的问题。下面是一个简单的Java Web点餐系统的代码示例:
```
// 1. 定义菜单项类
public class MenuItem {
private String name;
private String description;
private double price;
public MenuItem(String name, String description, double price) {
this.name = name;
this.description = description;
this.price = price;
}
// Getters and setters
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
// 2. 定义订单类
public class Order {
private List<MenuItem> items;
private String customerName;
public Order(String customerName) {
this.items = new ArrayList<>();
this.customerName = customerName;
}
public void addItem(MenuItem item) {
items.add(item);
}
public List<MenuItem> getItems() {
return items;
}
public String getCustomerName() {
return customerName;
}
}
// 3. 定义点餐系统Servlet
@WebServlet("/order")
public class OrderServlet extends HttpServlet {
private List<MenuItem> menu;
public void init() {
// 初始化菜单项
menu = new ArrayList<>();
menu.add(new MenuItem("炸鸡腿", "香酥可口的鸡肉", 10.99));
menu.add(new MenuItem("牛肉面", "牛肉加面条的经典组合", 8.99));
menu.add(new MenuItem("可乐", "松软可口的炭烤玉米", 2.99));
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 解析请求参数
String customerName = request.getParameter("customer_name");
String[] itemIds = request.getParameterValues("item_id");
// 构建订单
Order order = new Order(customerName);
for (String itemId : itemIds) {
int index = Integer.parseInt(itemId);
order.addItem(menu.get(index));
}
// 渲染订单页面
request.setAttribute("order", order);
RequestDispatcher dispatcher = request.getRequestDispatcher("order.jsp");
dispatcher.forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 渲染菜单选项页面
request.setAttribute("menu", menu);
RequestDispatcher dispatcher = request.getRequestDispatcher("menu.jsp");
dispatcher.forward(request, response);
}
}
```
以上代码基本上完成了一个简单的点餐系统的实现,包括了菜单选项、订单的创建和展示。您可以使用Java Servlet容器(如Tomcat)进行部署和运行该系统。具体的界面和样式效果需要另外编写相关的HTML和CSS代码。
阅读全文