【javaWeb技术】·外卖点餐小程序(介绍)
在这个JavaWeb技术的示例中,我们将创建一个简单的外卖点餐小程序。该程序将允许用户浏览可用的外卖品类,选择他们喜欢的商品,并将它们加入购物车。
// 假设有一个外卖品类的实体类
public class Dish {
private int id;
private String name;
private double price;
// 构造器、getter和setter省略
}
// 购物车类
public class Cart {
private List<Dish> items = new ArrayList<>();
public void addItem(Dish dish) {
items.add(dish);
}
public void removeItem(Dish dish) {
items.remove(dish);
}
public double getTotal() {
double total = 0.0;
for (Dish dish : items) {
total += dish.getPrice();
}
return total;
}
// 其他getter和setter省略
}
// 假设有一个Servlet处理用户请求
@WebServlet("/order")
public class OrderServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 假设有方法获取所有可用的外卖品类
List<Dish> dishes = getAllDishes();
request.setAttribute("dishes", dishes);
request.getRequestDispatcher("/order.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String dishId = request.getParameter("dishId");
Cart cart = getCartFromSession(request);
Dish dish = getDishById(dishId);
cart.addItem(dish);
response.sendRedirect("cart.jsp");
}
private Cart getCartFromSession(HttpServletRequest request) {
HttpSession session = request.getSession();
Cart cart = (Cart) session.getAttribute("cart");
if (cart == null) {
cart = new Cart();
session.setAttribute("cart", cart);
}
return cart;
}
// 获取所有可用外卖品类的方法、获取指定id的Dish方法等省略
}
上述代码展示了如何创建一个简单的外卖点餐系统的后端逻辑。在实际的应用中
评论已关闭