C3p0-config.xml <?xml version="1.0" encoding="UTF-8" ?> <c3p0-config> <default-config> <property name="jdbcUrl">jdbc:mysql://localhost:3306/hotel</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="user">root</property> <property name="password">xiongpan</property> <property name="acquireIncrement">3</property> <property name="initialPoolSize">10</property> <property name="minPoolSize">2</property> <property name="maxPoolSize">10</property> </default-config> </c3p0-config> 根据业务需求编写实体类 package com.xp.entity; import java.util.Date; public class DinnerTable { private int id; private String tableName; private int tableStatus; private Date orderDate; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public int getTableStatus() { return tableStatus; } public void setTableStatus(int tableStatus) { this.tableStatus = tableStatus; } public Date getOrderDate() { return orderDate; } public void setOrderDate(Date orderDate) { this.orderDate = orderDate; } @Override public String toString() { return "DinnerTable [id=" + id + ", tableName=" + tableName + ", tableStatus=" + tableStatus + ", orderDate=" + orderDate + "]"; } } package com.xp.entity; public class Food { private int id; private String foodName; private int foodType_id; private double price; private double mprice; private String remark; private String img; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFoodName() { return foodName; } public void setFoodName(String foodName) { this.foodName = foodName; } public int getFoodType_id() { return foodType_id; } public void setFoodType_id(int foodType_id) { this.foodType_id = foodType_id; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public double getMprice() { return mprice; } public void setMprice(double mprice) { this.mprice = mprice; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } @Override public String toString() { return "Food [id=" + id + ", foodName=" + foodName + ", foodType_id=" + foodType_id + ", price=" + price + ", mprice=" + mprice + ", remark=" + remark + ", img=" + img + "]"; } @Override public int hashCode() { return this.id; } @Override public boolean equals(Object obj) { Food f = (Food)obj; return f.getId()==this.id; } } package com.xp.entity; public class FoodType { private int id; private String typeName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } @Override public String toString() { return "FoodType [id=" + id + ", typeName=" + typeName + "]"; } } package com.xp.entity; import java.util.Date; public class Orders { private int id; //-- 主键 private int table_id;// -- 外键: 餐桌编号 private Date orderDate;//-- 下单日期 private double totalPrice;//-- 订单所有菜需要的总金额 private int orderStatus;// public int getId() { return id; } public void setId(int id) { this.id = id; } public int getTable_id() { return table_id; } public void setTable_id(int table_id) { this.table_id = table_id; } public Date getOrderDate() { return orderDate; } public void setOrderDate(Date orderDate) { this.orderDate = orderDate; } public double getTotalPrice() { return totalPrice; } public void setTotalPrice(double totalPrice) { this.totalPrice = totalPrice; } public int getOrderStatus() { return orderStatus; } public void setOrderStatus(int orderStatus) { this.orderStatus = orderStatus; } @Override public String toString() { return "Orders [id=" + id + ", table_id=" + table_id + ", orderDate=" + orderDate + ", totalPrice=" + totalPrice + ", orderStatus=" + orderStatus + "]"; } } package com.xp.entity; public class OrderDetail { private int id; // -- 主键 private int orderId;// -- 外键:引入的是订单表的主键 private int food_id ;//-- 外键:引用的是菜信息表的主键 private int foodCount; //-- 菜的数量 public int getId() { return id; } public void setId(int id) { this.id = id; } public int getOrderId() { return orderId; } public void setOrderId(int orderId) { this.orderId = orderId; } public int getFood_id() { return food_id; } public void setFood_id(int food_id) { this.food_id = food_id; } public int getFoodCount() { return foodCount; } public void setFoodCount(int foodCount) { this.foodCount = foodCount; } @Override public String toString() { return "OrderDetail [id=" + id + ", orderId=" + orderId + ", food_id=" + food_id + ", foodCount=" + foodCount + "]"; } } 编写常用工具类 package com.xp.utils; import javax.sql.DataSource; import org.apache.commons.dbutils.QueryRunner; import com.mchange.v2.c3p0.ComboPooledDataSource; public class JdbcUtils { // 初始化连接池 private static DataSource dataSource; static { dataSource = new ComboPooledDataSource(); } public static DataSource getDataSource() { return dataSource; } /** * 创建DbUtils常用工具类对象 */ public static QueryRunner getQuerrRunner() { return new QueryRunner(dataSource); } } package com.xp.utils; import java.io.IOException; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class WebUtils { /** * 跳转的通用方法 */ public static void goTo(HttpServletRequest request, HttpServletResponse response, Object uri) throws ServletException, IOException { if (uri instanceof RequestDispatcher){ ((RequestDispatcher)uri).forward(request, response); } else if (uri instanceof String) { response.sendRedirect(request.getContextPath() + uri); } } } package com.xp.utils; public class Condition { private String foodName; private int foodType_id; public String getFoodName() { return foodName; } public void setFoodName(String foodName) { this.foodName = foodName; } public int getFoodType_id() { return foodType_id; } public void setFoodType_id(int foodType_id) { this.foodType_id = foodType_id; } @Override public String toString() { return "Condition [foodName=" + foodName + ", foodType_id=" + foodType_id + "]"; } } package com.xp.utils; import java.util.List; public class PageBean<T> { private int currentPage = 1; // 当前页, 默认显示第一页 private int pageCount = 10; // 每页显示的行数(查询返回的行数), 默认每页显示4行 private int totalCount; // 总记录数 private int totalPage; // 总页数 = 总记录数 / 每页显示的行数 (+ 1) private List<T> pageData; // 分页查询到的数据 private Condition condition; public Condition getCondition() { return condition; } public void setCondition(Condition condition) { this.condition = condition; } // 返回总页数 public int getTotalPage() { if (totalCount % pageCount == 0) { totalPage = totalCount / pageCount; } else { totalPage = totalCount / pageCount + 1; } return totalPage; } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getPageCount() { return pageCount; } public void setPageCount(int pageCount) { this.pageCount = pageCount; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public List<T> getPageData() { return pageData; } public void setPageData(List<T> pageData) { this.pageData = pageData; } } 编写各接口 package com.xp.dao; import java.util.List; import com.xp.entity.DinnerTable; public interface IDinnerTableDao { void add(DinnerTable dt); void delete(int id); void updata(DinnerTable dt); List<DinnerTable> query(); DinnerTable findById(int id); List<DinnerTable> query(String keyword); void quitTable(int id); } package com.xp.dao; import java.util.List; import com.xp.entity.Food; import com.xp.utils.PageBean; public interface IFoodDao { void add(Food food); void delete(int id); void updata(Food food); List<Food> query(); Food findById(int id); List<Food> query(String keyword); List<Food> findByType(int type); /** * 分页查询数据 */ void getAll(PageBean<Food> pb); /** * 查询总记录数 */ int getTotalCount(PageBean<Food> pb); } package com.xp.dao; import java.util.List; import com.xp.entity.FoodType; public interface IFoodTypeDao { void add(FoodType foodtype); void delete(int id); void updata(FoodType foodtype); List<FoodType> query(); FoodType findById(int id); List<FoodType> query(String keyword); Integer getFirstType(); } package com.xp.dao; import java.util.List; import com.xp.entity.Orders; import com.xp.utils.PageBean; public interface IOrdersDao { void update(Orders orders); List<Orders> query(); void add(Orders orders); int getCount(); void getAll(PageBean<Orders> pb); int getTotalCount(); } package com.xp.dao; import java.util.List; import com.xp.entity.OrderDetail; public interface IOrderDetailDao { void add(OrderDetail od); List<OrderDetail> query(); List<OrderDetail> findByOrderid(int id); } package com.xp.dao.impl; import java.util.Date; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import com.xp.dao.IDinnerTableDao; import com.xp.entity.DinnerTable; import com.xp.utils.JdbcUtils; public class DinnerTableDao implements IDinnerTableDao{ private QueryRunner qr = JdbcUtils.getQuerrRunner(); @Override public void add(DinnerTable dt) { try { String sql = "INSERT dinnertable(tableName) VALUES(?)"; qr.update(sql, dt.getTableName()); } catch (Exception e) { throw new RuntimeException(e); } } @Override public DinnerTable findById(int id){ String sql = "select * from dinnertable where id=?"; try { return qr.query(sql, new BeanHandler<DinnerTable>(DinnerTable.class),id); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void delete(int id) { String sql = "delete from dinnertable where id=?"; try { qr.update(sql, id); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void updata(DinnerTable dt) { String sql = "UPDATE dinnertable SET tableStatus=?,orderDate=? WHERE id=?"; Date date = dt.getOrderDate(); try { JdbcUtils.getQuerrRunner().update(sql, dt.getTableStatus(),date,dt.getId()); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<DinnerTable> query(String keyword) { String sql = "SELECT * FROM dinnertable WHERE tableName LIKE ?"; try { return qr.query(sql, new BeanListHandler<DinnerTable>(DinnerTable.class),"%"+keyword +"%"); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<DinnerTable> query() { String sql = "select * from dinnertable"; try { return qr.query(sql, new BeanListHandler<DinnerTable>(DinnerTable.class)); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void quitTable(int id) { String sql = "UPDATE dinnertable SET tableStatus=?,orderDate=? WHERE id=?"; try { JdbcUtils.getQuerrRunner().update(sql,0,null,id); } catch (Exception e) { throw new RuntimeException(e); } } } package com.xp.dao.impl; import java.util.ArrayList; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import com.xp.dao.IFoodDao; import com.xp.entity.Food; import com.xp.utils.Condition; import com.xp.utils.JdbcUtils; import com.xp.utils.PageBean; public class FoodDao implements IFoodDao { private QueryRunner qr = JdbcUtils.getQuerrRunner(); @Override public void add(Food food) { String sql = " INSERT food(foodName,foodType_id,price,mprice,remark,img) VALUES(?,?,?,?,?,?);"; try { qr.update(sql, food.getFoodName(), food.getFoodType_id(), food.getPrice(), food.getMprice(), food.getRemark(), food.getImg()); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void delete(int id) { try { String sql = "DELETE FROM food WHERE id=?"; qr.update(sql, id); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void updata(Food food) { try { String sql = "UPDATE food SET foodName=?,foodType_id=?,price=?,mprice=?,remark=?,img=? WHERE id =?"; qr.update(sql, food.getFoodName(), food.getFoodType_id(), food.getPrice(), food.getMprice(), food.getRemark(), food.getImg(), food.getId()); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<Food> query() { try { String sql = "SELECT * FROM food"; return qr.query(sql, new BeanListHandler<Food>(Food.class)); } catch (Exception e) { throw new RuntimeException(e); } } @Override public Food findById(int id) { try { String sql = "SELECT * FROM food where id =?"; return qr.query(sql, new BeanHandler<Food>(Food.class), id); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<Food> query(String keyword) { try { String sql = "SELECT * FROM food WHERE foodName LIKE ?"; return qr.query(sql, new BeanListHandler<Food>(Food.class), "%" + keyword + "%"); } catch (Exception e) { throw new RuntimeException(e); } } @Override public int getTotalCount(PageBean<Food> pb) { StringBuilder sb = new StringBuilder(); List<Object> list = new ArrayList<Object>(); sb.append(" SELECT"); sb.append(" count(*) "); sb.append(" FROM "); sb.append(" food f,"); sb.append(" foodtype ft"); sb.append(" WHERE 1=1 "); sb.append(" AND f.foodType_id=ft.id"); Condition condition = pb.getCondition(); // 判断 if (condition != null) { String foodName = condition.getFoodName(); if (foodName != null && !foodName.isEmpty()) { sb.append(" AND f.foodName LIKE ? "); list.add("%" + foodName + "%"); } int type_id = condition.getFoodType_id(); if (type_id > 0) { sb.append(" AND f.foodType_id=? "); list.add(type_id); } } try { // 执行查询, 返回结果的第一行的第一列 Long count = qr.query(sb.toString(), new ScalarHandler<Long>(), list.toArray()); return count.intValue(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void getAll(PageBean<Food> pb) { // 2. 查询总记录数; 设置到pb对象中 int totalCount = this.getTotalCount(pb); pb.setTotalCount(totalCount); List<Object> list = new ArrayList<Object>(); /* * 问题: jsp页面,如果当前页为首页,再点击上一页报错! 如果当前页为末页,再点下一页显示有问题! 解决: 1. 如果当前页 <= 0; * 当前页设置当前页为1; 2. 如果当前页 > 最大页数; 当前页设置为最大页数 */ // 判断 if (pb.getCurrentPage() <= 0) { pb.setCurrentPage(1); // 把当前页设置为1 } else if (pb.getCurrentPage() > pb.getTotalPage()) { pb.setCurrentPage(pb.getTotalPage()); // 把当前页设置为最大页数 } // 1. 获取当前页: 计算查询的起始行、返回的行数 int currentPage = pb.getCurrentPage(); int index = (currentPage - 1) * pb.getPageCount(); // 查询的起始行 int count = pb.getPageCount(); // 查询返回的行数 Condition condition = pb.getCondition(); // 3. 分页查询数据; 把查询到的数据设置到pb对象中 // String sql = "select * from food limit ?,?"; StringBuilder sb = new StringBuilder(); sb.append(" SELECT"); sb.append(" f.id,"); sb.append(" f.foodName,"); sb.append(" f.foodType_id,"); sb.append(" f.price,"); sb.append(" f.mprice,"); sb.append(" f.remark,"); sb.append(" f.img,"); sb.append(" ft.typeName"); sb.append(" FROM "); sb.append(" food f,"); sb.append(" foodtype ft"); sb.append(" WHERE 1=1 "); sb.append(" AND f.foodType_id=ft.id"); // 判断 if (condition != null) { String foodName = condition.getFoodName(); if (foodName != null && !foodName.isEmpty()) { sb.append(" AND f.foodName LIKE ? "); list.add("%" + foodName + "%"); } int type_id = condition.getFoodType_id(); if (type_id > 0) { sb.append(" AND f.foodType_id=? "); list.add(type_id); } } sb.append(" limit ?,? "); list.add(index); list.add(count); try { // 根据当前页,查询当前页数据(一页数据) if (index >= 0) { List<Food> pageData = qr.query(sb.toString(), new BeanListHandler<Food>(Food.class), list.toArray()); // 设置到pb对象中 pb.setPageData(pageData); } } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<Food> findByType(int type) { try { // 根据食物类型找到食物 String sql = "SELECT * FROM food WHERE foodType_id =?"; return qr.query(sql, new BeanListHandler<Food>(Food.class), type); } catch (Exception e) { throw new RuntimeException(e); } } } package com.xp.dao.impl; import java.sql.SQLException; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import com.xp.dao.IFoodTypeDao; import com.xp.entity.FoodType; import com.xp.utils.JdbcUtils; public class FoodTypeDao implements IFoodTypeDao{ private QueryRunner qr = JdbcUtils.getQuerrRunner(); @Override public Integer getFirstType() { try { String sql = "select * from foodtype"; return qr.query(sql, new ScalarHandler<Integer>()); } catch (SQLException e) { throw new RuntimeException(e); } } @Override public void add(FoodType foodtype) { try { String sql ="INSERT INTO foodtype(typeName) VALUES(?);"; qr.update(sql, foodtype.getTypeName()); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void delete(int id) { try { String sql ="DELETE FROM foodtype WHERE id=?"; qr.update(sql,id); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void updata(FoodType foodtype) { try { String sql ="UPDATE foodtype SET typeName=? WHERE id =?"; qr.update(sql,foodtype.getTypeName(),foodtype.getId()); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<FoodType> query() { try { String sql ="SELECT * FROM foodtype"; return qr.query(sql,new BeanListHandler<FoodType>(FoodType.class)); } catch (Exception e) { throw new RuntimeException(e); } } @Override public FoodType findById(int id) { try { String sql ="SELECT * FROM foodtype where id =?"; return qr.query(sql,new BeanHandler<FoodType>(FoodType.class), id); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<FoodType> query(String keyword) { try { String sql ="SELECT * FROM foodtype WHERE typeName LIKE ?"; return qr.query(sql,new BeanListHandler<FoodType>(FoodType.class) , "%"+keyword+"%"); } catch (Exception e) { throw new RuntimeException(e); } } } package com.xp.dao.impl; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import com.xp.dao.IOrdersDao; import com.xp.entity.Orders; import com.xp.utils.JdbcUtils; import com.xp.utils.PageBean; public class OrdersDao implements IOrdersDao{ private QueryRunner qr = JdbcUtils.getQuerrRunner(); @Override public void add(Orders orders) { String sql =" INSERT orders(table_id,orderDate,totalPrice) VALUES(?,?,?)"; try { qr.update(sql,orders.getTable_id(),orders.getOrderDate(),orders.getTotalPrice()); } catch (Exception e) { throw new RuntimeException(e); } } public int getCount(){ String sql ="select count(*) from orders"; try { Long count = qr.query(sql, new ScalarHandler<Long>()); return count.intValue(); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void update(Orders orders) { String sql = "UPDATE orders SET orderStatus =? WHERE id=?"; try { qr.update(sql,orders.getOrderStatus(),orders.getId()); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<Orders> query() { String sql = "SELECT * FROM orders"; try { return qr.query(sql, new BeanListHandler<Orders>(Orders.class)); } catch (Exception e) { throw new RuntimeException(e); } } @Override public void getAll(PageBean<Orders> pb) { //2. 查询总记录数; 设置到pb对象中 int totalCount = this.getTotalCount(); pb.setTotalCount(totalCount); /* * 问题: jsp页面,如果当前页为首页,再点击上一页报错! * 如果当前页为末页,再点下一页显示有问题! * 解决: * 1. 如果当前页 <= 0; 当前页设置当前页为1; * 2. 如果当前页 > 最大页数; 当前页设置为最大页数 */ // 判断 if (pb.getCurrentPage() <=0) { pb.setCurrentPage(1); // 把当前页设置为1 } else if (pb.getCurrentPage() > pb.getTotalPage()){ pb.setCurrentPage(pb.getTotalPage()); // 把当前页设置为最大页数 } //1. 获取当前页: 计算查询的起始行、返回的行数 int currentPage = pb.getCurrentPage(); int index = (currentPage -1 ) * pb.getPageCount(); // 查询的起始行 int count = pb.getPageCount(); // 查询返回的行数 //3. 分页查询数据; 把查询到的数据设置到pb对象中 String sql = "select * from orders limit ?,?"; try { // 根据当前页,查询当前页数据(一页数据) List<Orders> pageData = qr.query(sql, new BeanListHandler<Orders>(Orders.class), index, count); // 设置到pb对象中 pb.setPageData(pageData); } catch (Exception e) { throw new RuntimeException(e); } } @Override public int getTotalCount() { String sql = "select count(*) from orders"; try { // 执行查询, 返回结果的第一行的第一列 Long count = qr.query(sql, new ScalarHandler<Long>()); return count.intValue(); } catch (Exception e) { throw new RuntimeException(e); } } } package com.xp.dao.impl; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanListHandler; import com.xp.dao.IOrderDetailDao; import com.xp.entity.OrderDetail; import com.xp.utils.JdbcUtils; public class OrderDetailDao implements IOrderDetailDao { private QueryRunner qr = JdbcUtils.getQuerrRunner(); @Override public void add(OrderDetail od) { String sql =" INSERT orderdetail(orderId,food_id,foodCount) VALUES(?,?,?)"; try { qr.update(sql,od.getOrderId(),od.getFood_id(),od.getFoodCount()); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<OrderDetail> query() { try { String sql ="SELECT * FROM orderdetail"; return qr.query(sql,new BeanListHandler<OrderDetail>(OrderDetail.class)); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<OrderDetail> findByOrderid(int id) { try { String sql ="SELECT * FROM orderdetail where orderId=?"; return qr.query(sql,new BeanListHandler<OrderDetail>(OrderDetail.class),id); } catch (Exception e) { throw new RuntimeException(e); } } } package com.xp.service; import java.util.List; import com.xp.entity.DinnerTable; public interface IDinnerTableService { void add(DinnerTable dt); void delete(int id); void updata(DinnerTable dt); List<DinnerTable> query(); DinnerTable findById(int id); List<DinnerTable> query(String keyword); DinnerTable changeState(int id); void quitTable(int id); } package com.xp.service; import java.util.List; import com.xp.entity.Food; import com.xp.utils.PageBean; public interface IFoodService { void delete(int id); void updata(Food food); List<Food> query(); Food findById(int id); List<Food> query(String keyword); public void getAll(PageBean<Food> pb); List<Food> findByType(int type); void add(Food food); } package com.xp.service; import java.util.List; import com.xp.entity.FoodType; public interface IFoodTypeService { void add(FoodType foodtype); void delete(int id); void updata(FoodType foodtype); List<FoodType> query(); FoodType findById(int id); List<FoodType> query(String keyword); Integer getFirstType(); } package com.xp.service; import java.util.List; import com.xp.entity.Orders; import com.xp.utils.PageBean; public interface IOrdersService { void update(Orders orders); List<Orders> query(); void add(Orders orders); int getCount(); public void getAll(PageBean<Orders> pb); } package com.xp.service; import java.util.List; import com.xp.entity.OrderDetail; public interface IOrderDetailService { void add(OrderDetail od); List<OrderDetail> query(); List<OrderDetail> findByOrderId(int id); } package com.xp.factory; import java.util.ResourceBundle; public class BeanFactory { private static ResourceBundle bundle ; static{ bundle = ResourceBundle.getBundle("instance"); } public static <T> T getInstance(String key,Class<T> clazz){ try { String className = bundle.getString(key); return (T) Class.forName(className).newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } } package com.xp.service.impl; import java.util.Date; import java.util.List; import com.xp.dao.IDinnerTableDao; import com.xp.entity.DinnerTable; import com.xp.factory.BeanFactory; import com.xp.service.IDinnerTableService; public class DinnerTableService implements IDinnerTableService{ IDinnerTableDao dao = BeanFactory.getInstance("dinnerTableDao", IDinnerTableDao.class); @Override public void add(DinnerTable dt) { dao.add(dt); } @Override public void delete(int id) { dao.delete(id); } @Override public void updata(DinnerTable dt) { dao.updata(dt); } @Override public List<DinnerTable> query(String keyword) { return dao.query(keyword); } @Override public List<DinnerTable> query() { return dao.query(); } @Override public DinnerTable changeState(int id) { DinnerTable table = dao.findById(id); int status = table.getTableStatus(); if(status==0){ status=1; Date date = new Date(); table.setOrderDate(date); }else if(status==1){ status=0; table.setOrderDate(null); } table.setTableStatus(status); dao.updata(table); return table; } @Override public DinnerTable findById(int id) { return dao.findById(id); } @Override public void quitTable(int id) { dao.quitTable(id); } } package com.xp.service.impl; import java.util.List; import com.xp.dao.IFoodDao; import com.xp.entity.Food; import com.xp.factory.BeanFactory; import com.xp.service.IFoodService; import com.xp.utils.PageBean; public class FoodService implements IFoodService{ IFoodDao dao = BeanFactory.getInstance("foodDao", IFoodDao.class); public void add(Food food) { dao.add(food); } @Override public void delete(int id) { dao.delete(id); } @Override public void updata(Food food) { dao.updata(food); } @Override public List<Food> query() { return dao.query(); } @Override public Food findById(int id) { return dao.findById(id); } @Override public List<Food> query(String keyword) { return dao.query(keyword); } @Override public void getAll(PageBean<Food> pb) { try { dao.getAll(pb); } catch (Exception e) { throw new RuntimeException(e); } } @Override public List<Food> findByType(int type) { return dao.findByType(type); } } package com.xp.service.impl; import java.util.List; import com.xp.dao.IFoodTypeDao; import com.xp.entity.FoodType; import com.xp.factory.BeanFactory; import com.xp.service.IFoodTypeService; public class FoodTypeService implements IFoodTypeService{ IFoodTypeDao dao = BeanFactory.getInstance("foodTypeDao", IFoodTypeDao.class) ; @Override public void add(FoodType foodtype) { dao.add(foodtype); } @Override public void delete(int id) { dao.delete(id); } @Override public void updata(FoodType foodtype) { dao.updata(foodtype); } @Override public List<FoodType> query() { return dao.query(); } @Override public FoodType findById(int id) { return dao.findById(id); } @Override public List<FoodType> query(String keyword) { return dao.query(keyword); } @Override public Integer getFirstType() { return dao.getFirstType(); } } package com.xp.service.impl; import java.util.List; import com.xp.dao.IOrderDetailDao; import com.xp.entity.OrderDetail; import com.xp.factory.BeanFactory; import com.xp.service.IOrderDetailService; public class OrderDetailService implements IOrderDetailService{ IOrderDetailDao dao = BeanFactory.getInstance("orderDetailDao", IOrderDetailDao.class); public void add(OrderDetail od) { dao.add(od); } @Override public List<OrderDetail> query() { return dao.query(); } @Override public List<OrderDetail> findByOrderId(int id) { return dao.findByOrderid(id); } } package com.xp.service.impl; import java.util.List; import com.xp.dao.IOrdersDao; import com.xp.entity.Orders; import com.xp.factory.BeanFactory; import com.xp.service.IOrdersService; import com.xp.utils.PageBean; public class OrdersService implements IOrdersService{ IOrdersDao dao = BeanFactory.getInstance("ordersDao", IOrdersDao.class); @Override public void update(Orders orders) { dao.update(orders); } @Override public List<Orders> query() { return dao.query(); } @Override public void add(Orders orders) { dao.add(orders); } @Override public int getCount() { return dao.getCount(); } @Override public void getAll(PageBean<Orders> pb) { try { dao.getAll(pb); } catch (Exception e) { throw new RuntimeException(e); } } } package com.xp.servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.xp.entity.DinnerTable; import com.xp.factory.BeanFactory; import com.xp.service.IDinnerTableService; public class DinnerTableServlet extends HttpServlet { private static final long serialVersionUID = 6626870982046623887L; private IDinnerTableService service = BeanFactory.getInstance("dinnerTableService", IDinnerTableService.class); @Override public void init(ServletConfig config) throws ServletException { super.init(config); List<DinnerTable> list = service.query(); config.getServletContext().setAttribute("table", list); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method = request.getParameter("method"); if("add".equals(method)){ add(request,response); }else if("list".equals(method)){ list(request,response); }else if("up1".equals(method)){ update(request,response); }else if("delete".equals(method)){ delete(request,response); }else if("search".equals(method)){ search(request,response); } } private void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String keyword = request.getParameter("keyword"); if(keyword!=null){ List<DinnerTable> list = service.query(keyword); request.setAttribute("list",list); request.getRequestDispatcher("/sys/board/boardList.jsp").forward(request, response); } } private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); service.delete(Integer.parseInt(id)); list(request, response); } private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ String id = request.getParameter("id"); service.changeState(Integer.parseInt(id)); list(request, response); } private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ List<DinnerTable> list = service.query(); request.setAttribute("list",list); //将餐桌列表存到context里传到前台显示 request.getServletContext().setAttribute("table", list); request.getRequestDispatcher("/sys/board/boardList.jsp").forward(request, response); } private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ String tableName = request.getParameter("tableName"); if(tableName!=null){ DinnerTable dt = new DinnerTable(); dt.setTableName(tableName); service.add(dt); list(request, response); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } package com.xp.servlet; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.xp.entity.FoodType; import com.xp.factory.BeanFactory; import com.xp.service.IFoodTypeService; public class FoodTypeServlet extends HttpServlet { private IFoodTypeService service = BeanFactory.getInstance("foodTypeService", IFoodTypeService.class); private Object uri; @Override public void init(ServletConfig config) throws ServletException { super.init(config); List<FoodType> list = service.query(); config.getServletContext().setAttribute("foodtype", list); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method = request.getParameter("method"); if("add".equals(method)){ add(request,response); }else if("list".equals(method)){ list(request,response); }else if("update".equals(method)){ update(request,response); }else if("delete".equals(method)){ delete(request,response); }else if("search".equals(method)){ search(request,response); }else if("show".equals(method)){ show(request, response); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String name = request.getParameter("name"); FoodType foodtype = new FoodType(); foodtype.setTypeName(name); service.add(foodtype); list(request, response); } catch (Exception e) { e.printStackTrace(); uri="/error/error.jsp"; } } private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { List<FoodType> list = service.query(); request.setAttribute("list", list); request.getServletContext().setAttribute("foodtype", list); uri = request.getRequestDispatcher("/sys/foodtype/cuisineList.jsp"); } catch (Exception e) { e.printStackTrace(); uri="/error/error.jsp"; }finally { goTo(request, response,uri); } } private void goTo(HttpServletRequest request, HttpServletResponse response,Object uri) throws ServletException, IOException { if(uri instanceof RequestDispatcher){ ((RequestDispatcher) uri).forward(request, response); }else{ response.sendRedirect(request.getContextPath()+(String)uri); } } //在菜系更新中显示菜系对应的类型的名称 private void show(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String id = request.getParameter("id"); FoodType type = service.findById(Integer.parseInt(id)); request.setAttribute("type", type); uri = request.getRequestDispatcher("/sys/foodtype/updateCuisine.jsp"); } catch (Exception e) { e.printStackTrace(); uri="/error/error.jsp"; }finally { goTo(request, response,uri); } } private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { FoodType type = new FoodType(); Map<String, String[]> map = request.getParameterMap(); BeanUtils.populate(type, map); service.updata(type); list(request, response); } catch (Exception e) { e.printStackTrace(); uri="/error/error.jsp"; } } private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String id = request.getParameter("id"); service.delete(Integer.parseInt(id)); list(request, response); } catch (Exception e) { e.printStackTrace(); uri="/error/error.jsp"; goTo(request, response, uri); } } private void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String keyword = request.getParameter("keyword"); if(keyword!=null){ List<FoodType> list = service.query(keyword); request.setAttribute("list",list); uri=request.getRequestDispatcher("/sys/foodtype/cuisineList.jsp"); } } catch (Exception e) { uri="/error/error.jsp"; e.printStackTrace(); } goTo(request, response, uri); } } package com.xp.servlet; import java.io.IOException; import java.util.List; import java.util.Map; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils; import com.xp.entity.FoodType; import com.xp.factory.BeanFactory; import com.xp.service.IFoodTypeService; public class FoodTypeServlet extends HttpServlet { private static final long serialVersionUID = -6692273290397726221L; private IFoodTypeService service = BeanFactory.getInstance("foodTypeService", IFoodTypeService.class); private Object uri; @Override public void init(ServletConfig config) throws ServletException { super.init(config); List<FoodType> list = service.query(); config.getServletContext().setAttribute("foodtype", list); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method = request.getParameter("method"); if("add".equals(method)){ add(request,response); }else if("list".equals(method)){ list(request,response); }else if("update".equals(method)){ update(request,response); }else if("delete".equals(method)){ delete(request,response); }else if("search".equals(method)){ search(request,response); }else if("show".equals(method)){ show(request, response); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String name = request.getParameter("name"); FoodType foodtype = new FoodType(); foodtype.setTypeName(name); service.add(foodtype); list(request, response); } catch (Exception e) { e.printStackTrace(); uri="/error/error.jsp"; } } private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { List<FoodType> list = service.query(); request.setAttribute("list", list); request.getServletContext().setAttribute("foodtype", list); uri = request.getRequestDispatcher("/sys/foodtype/cuisineList.jsp"); } catch (Exception e) { e.printStackTrace(); uri="/error/error.jsp"; }finally { goTo(request, response,uri); } } private void goTo(HttpServletRequest request, HttpServletResponse response,Object uri) throws ServletException, IOException { if(uri instanceof RequestDispatcher){ ((RequestDispatcher) uri).forward(request, response); }else{ response.sendRedirect(request.getContextPath()+(String)uri); } } //在菜系更新中显示菜系对应的类型的名称 private void show(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String id = request.getParameter("id"); FoodType type = service.findById(Integer.parseInt(id)); request.setAttribute("type", type); uri = request.getRequestDispatcher("/sys/foodtype/updateCuisine.jsp"); } catch (Exception e) { e.printStackTrace(); uri="/error/error.jsp"; }finally { goTo(request, response,uri); } } private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { FoodType type = new FoodType(); Map<String, String[]> map = request.getParameterMap(); BeanUtils.populate(type, map); service.updata(type); list(request, response); } catch (Exception e) { e.printStackTrace(); uri="/error/error.jsp"; } } private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String id = request.getParameter("id"); service.delete(Integer.parseInt(id)); list(request, response); } catch (Exception e) { e.printStackTrace(); uri="/error/error.jsp"; goTo(request, response, uri); } } private void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String keyword = request.getParameter("keyword"); if(keyword!=null){ List<FoodType> list = service.query(keyword); request.setAttribute("list",list); uri=request.getRequestDispatcher("/sys/foodtype/cuisineList.jsp"); } } catch (Exception e) { uri="/error/error.jsp"; e.printStackTrace(); } goTo(request, response, uri); } } package com.xp.servlet; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.xp.entity.Food; import com.xp.entity.FoodType; import com.xp.factory.BeanFactory; import com.xp.service.IFoodService; import com.xp.service.IFoodTypeService; import com.xp.utils.PageBean; public class FoodServlet extends HttpServlet { private static final long serialVersionUID = 1L; private IFoodService service = BeanFactory.getInstance("foodService", IFoodService.class); private IFoodTypeService ifs = BeanFactory.getInstance("foodTypeService", IFoodTypeService.class); private Object uri; @Override public void init(ServletConfig config) throws ServletException { super.init(config); PageBean<Food> pageBean = new PageBean<Food>(); pageBean.setPageCount(6); service.getAll(pageBean); List<Food> list = service.query(); config.getServletContext().setAttribute("food", list); config.getServletContext().setAttribute("pb", pageBean); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String method = request.getParameter("method"); if ("add".equals(method)) { add(request, response); } else if ("list".equals(method)) { list(request, response); } else if ("update".equals(method)) { update(request, response); } else if ("delete".equals(method)) { delete(request, response); } else if ("search".equals(method)) { search(request, response); } else if ("show".equals(method)) { show(request, response); } else if ("findFoodType".equals(method)) { findFoodType(request, response); uri = request.getRequestDispatcher("/sys/food/saveFood.jsp"); goTo(request, response, uri); } else if ("query".equals(method)) { query(request, response); } else if ("getMenu".equals(method)) { getMenu(request, response); } } private void getMenu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // 1. 获取“当前页”参数; (第一次访问当前页为null) String currPage = request.getParameter("currentPage"); // 判断 if (currPage == null || "".equals(currPage.trim())) { currPage = "1"; // 第一次访问,设置当前页为1; } // 转换 int currentPage = Integer.parseInt(currPage); // 2. 创建PageBean对象,设置当前页参数; 传入service方法参数 PageBean<Food> pageBean = new PageBean<Food>(); pageBean.setCurrentPage(currentPage); // 3. 调用service service.getAll(pageBean); // 【pageBean已经被dao填充了数据】 // 4. 保存pageBean对象,到request域中 List<Food> list = pageBean.getPageData(); // 获得食物类别的方法 List<FoodType> types = new ArrayList<FoodType>(); if (list != null) { for (Food food : list) { FoodType foodtype = ifs.findById(food.getFoodType_id()); types.add(foodtype); } } request.setAttribute("types", types); request.setAttribute("pageBean", pageBean); request.setAttribute("list", list); uri = request.getRequestDispatcher("/sys/food/foodList.jsp"); } catch (Exception e) { e.printStackTrace(); // 测试使用 // 出现错误,跳转到错误页面;给用户友好提示 uri = "/error/error.jsp"; } goTo(request, response, uri); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public void findFoodType(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<FoodType> foodtypes = ifs.query(); request.setAttribute("foodtypes", foodtypes); } private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(10 * 1024 * 1024); // 单个文件大小限制 upload.setSizeMax(50 * 1024 * 1024); // 总文件大小限制 upload.setHeaderEncoding("UTF-8"); // 对中文文件编码处理 if (upload.isMultipartContent(request)) { Food food = new Food(); List<FileItem> list = upload.parseRequest(request); for (FileItem item : list) { if (item.isFormField()) {// 普通本文内容 String name = item.getFieldName(); // 获取值 String value = item.getString(); value = new String(value.getBytes("ISO-8859-1"), "UTF-8"); BeanUtils.setProperty(food, name, value); } else {// 上传内容 String fieldName = item.getFieldName(); String path = getServletContext() .getRealPath("/upload"); File f = new File(path); if (!f.exists()) { f.mkdir(); } // 全部绝对路径 String name = item.getName(); BeanUtils .setProperty(food, fieldName, "upload/" + name); // a2. 拼接文件名 File file = new File(path, name); // d. 上传 if(!file.isDirectory()){ item.write(file); } item.delete(); // 删除组件运行时产生的临时文件 } } service.add(food); } else { } list(request, response); } catch (Exception e) { e.printStackTrace(); uri = "/error/error.jsp"; goTo(request, response, uri); } } private void query(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { List<Food> list = service.query(); request.setAttribute("list", list); // 获得食物类别的方法 List<FoodType> types = new ArrayList<FoodType>(); IFoodTypeService ifs = BeanFactory.getInstance("foodTypeService", IFoodTypeService.class); for (Food food : list) { FoodType foodtype = ifs.findById(food.getFoodType_id()); types.add(foodtype); } request.setAttribute("types", types); uri = request.getRequestDispatcher("/sys/food/foodList.jsp"); } catch (Exception e) { e.printStackTrace(); uri = "/error/error.jsp"; } finally { goTo(request, response, uri); } } private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(10 * 1024 * 1024); // 单个文件大小限制 upload.setSizeMax(50 * 1024 * 1024); // 总文件大小限制 upload.setHeaderEncoding("UTF-8"); // 对中文文件编码处理 if (upload.isMultipartContent(request)) { Food food = new Food(); List<FileItem> list = upload.parseRequest(request); for (FileItem item : list) { if (item.isFormField()) {// 普通本文内容 String name = item.getFieldName(); // 获取值 String value = item.getString(); value = new String(value.getBytes("ISO-8859-1"), "UTF-8"); BeanUtils.setProperty(food, name, value); } else {// 上传内容 String fieldName = item.getFieldName(); String path = getServletContext() .getRealPath("/upload"); File f = new File(path); if (!f.exists()) { f.mkdir(); } String name = item.getName(); if(name!=null && !"".equals(name.trim())){ BeanUtils.setProperty(food, fieldName, ("upload/" + name)); // a2. 拼接文件名 File file = new File(path, name); // d. 上传 if (!file.isDirectory()) { item.write(file); } item.delete(); // 删除组件运行时产生的临时文件 }else{ int id = food.getId(); String img =service.findById(id).getImg(); BeanUtils.setProperty(food, "img",img); } } } service.updata(food); } else { } list(request, response); } catch (Exception e) { e.printStackTrace(); uri = "/error/error.jsp"; goTo(request, response, uri); } } private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String id = request.getParameter("id"); service.delete(Integer.parseInt(id)); list(request, response); } catch (Exception e) { e.printStackTrace(); uri = "/error/error.jsp"; goTo(request, response, uri); } } private void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { String keyword = request.getParameter("keyword"); if (keyword != null) { List<Food> list = service.query(keyword); List<FoodType> types = new ArrayList<FoodType>(); if (list != null) { for (Food food : list) { FoodType foodtype = ifs.findById(food.getFoodType_id()); types.add(foodtype); } } request.setAttribute("types", types); request.setAttribute("list", list); uri = request.getRequestDispatcher("/sys/food/foodList.jsp"); } } catch (Exception e) { uri = "/error/error.jsp"; e.printStackTrace(); } goTo(request, response, uri); } // 这个方法没用 private void show(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { findFoodType(request, response); String id = request.getParameter("id"); Food food = service.findById(Integer.parseInt(id)); request.setAttribute("food", food); // 得到食物里面的食物类型ID int foodType_id = food.getFoodType_id(); // 通过 FoodType type = ifs.findById(foodType_id); request.setAttribute("type", type); uri = request.getRequestDispatcher("/sys/food/updateFood.jsp"); goTo(request, response, uri); } private void goTo(HttpServletRequest request, HttpServletResponse response, Object uri) throws ServletException, IOException { if (uri instanceof RequestDispatcher) { ((RequestDispatcher) uri).forward(request, response); } else { response.sendRedirect(request.getContextPath() + (String) uri); } } } package com.xp.servlet; import java.io.IOException; import java.lang.reflect.Method; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.xp.factory.BeanFactory; import com.xp.service.IDinnerTableService; import com.xp.service.IFoodService; import com.xp.service.IFoodTypeService; import com.xp.service.IOrderDetailService; import com.xp.service.IOrdersService; import com.xp.utils.WebUtils; public abstract class BaseServlet extends HttpServlet { // 创建Service protected IDinnerTableService tableService = BeanFactory.getInstance( "dinnerTableService", IDinnerTableService.class); protected IFoodTypeService foodTypeService = BeanFactory.getInstance( "foodTypeService", IFoodTypeService.class); protected IFoodService foodService = BeanFactory.getInstance("foodService", IFoodService.class); protected IOrdersService ordersService = BeanFactory.getInstance("ordersService", IOrdersService.class); protected IOrderDetailService orderDetailService = BeanFactory.getInstance("orderDetailService", IOrderDetailService.class); @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // (保存跳转的资源) 方法返回值 Object returnValue = null; // 获取操作类型; 【约定 > 俗成: 操作类型的值,必须对应servlet中的方法名称】 String methodName = request.getParameter("method"); // listTable try { // 1. 获取当前运行类的字节码 Class clazz = this.getClass(); // 2. 获取当前执行的方法的Method类型 Method method = clazz.getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class); // 3. 执行方法 returnValue = method.invoke(this, request,response); } catch (Exception e) { e.printStackTrace(); returnValue = "/error/error.jsp"; } // 跳转 WebUtils.goTo(request, response, returnValue); } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } } package com.xp.servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.xp.entity.Food; import com.xp.entity.FoodType; import com.xp.utils.Condition; import com.xp.utils.PageBean; public class IndexServlet extends BaseServlet { public Object getMenu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object uri = null; HttpSession session = request.getSession();// 用于存储订单信息 // 获取session里的值 Object obj = session.getAttribute("table_id"); String table_id = request.getParameter("table_id");// 桌的id if (table_id != null) { tableService.changeState(Integer.parseInt(table_id)); if (obj == null) { session.setAttribute("table_id", table_id);// 存放桌id以备订单用 } } // 查询菜系信息 List<FoodType> foodtypes = foodTypeService.query(); request.setAttribute("foodtypes", foodtypes); // 获取菜单页面信息 PageBean<Food> pb = new PageBean<Food>(); Condition con = new Condition(); // 获取页面得到的参数 String foodtype = request.getParameter("foodtype"); String foodName = request.getParameter("foodName"); if (foodtype != null && !foodtype.isEmpty()) { con.setFoodType_id(Integer.parseInt(foodtype)); pb.setCondition(con); } if (foodName != null && !foodName.isEmpty()) { con.setFoodName(foodName); pb.setCondition(con); } pb.setPageCount(6); String curPage = request.getParameter("currentPage");// 获取当前页 if (curPage == null || curPage.isEmpty()) { pb.setCurrentPage(1); } if (curPage != null && !curPage.isEmpty()) { int currentPage = Integer.parseInt(curPage); pb.setCurrentPage(currentPage); } foodService.getAll(pb); request.setAttribute("pageBean", pb); // 跳转 uri = request.getRequestDispatcher("/app/detail/caidan.jsp"); return uri; } public Object searchFood(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object uri=null; PageBean<Food> pb = new PageBean<Food>(); Condition condition = new Condition(); String keyword = request.getParameter("keyword");//设置关键词 if(keyword!=null && !keyword.isEmpty()){ condition.setFoodName(keyword); } if(condition!=null){ pb.setCondition(condition); } pb.setCondition(condition); foodService.getAll(pb); request.setAttribute("pageBean", pb); // 跳转 uri = request.getRequestDispatcher("/app/detail/caidan.jsp"); return uri; } public Object getFoodDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object uri =null; String id = request.getParameter("food");//获取食物id Food food = foodService.findById(Integer.parseInt(id)); List<FoodType> foodtypes = foodTypeService.query(); request.setAttribute("food", food); request.setAttribute("foodtypes", foodtypes); uri = request.getRequestDispatcher("/app/detail/caixiangxi.jsp"); return uri; } //下面是关于订单的方法 /*public Object putInCar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); Object uri =null; Map<Food,Integer> map = new LinkedHashMap<Food,Integer>(); //获取食物id String id = request.getParameter("food_id"); Food food = foodService.findById(Integer.parseInt(id)); Map<Food,Integer> m =(Map<Food, Integer>) session.getAttribute("foods"); if(m!=null){ if(m.containsKey(food)){ Integer count = m.get(food); count++; m.put(food, count); }else{ m.put(food, 1); } }else { map.put(food, 1); } if(m!=null){ session.setAttribute("foods", m); }else{ session.setAttribute("foods", map); } uri="/app/detail/clientCart.jsp"; return uri; } public Object removeOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object uri=null; String id = request.getParameter("gid"); Food food = foodService.findById(Integer.parseInt(id)); HttpSession session = request.getSession(); Map<Food,Integer> m= (Map<Food,Integer>)session.getAttribute("foods"); m.remove(food); session.setAttribute("foods", m); uri="/app/detail/clientCart.jsp"; return uri; } public Object alterSorder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object uri=null; String id = request.getParameter("gid"); Food food = foodService.findById(Integer.parseInt(id)); //获取修改狗的数量 String num = request.getParameter("snumber"); HttpSession session = request.getSession(); Map<Food,Integer> m= (Map<Food,Integer>)session.getAttribute("foods"); m.put(food, Integer.parseInt(num)); session.setAttribute("foods", m); uri="/app/detail/clientCart.jsp"; return uri; } public Object takeOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object uri=null; HttpSession session = request.getSession(); Map<Food,Integer> m = (Map<Food,Integer>)session.getAttribute("foods"); String table_id =(String)session.getAttribute("table_id"); //新建订单对象 Orders order = new Orders(); order.setTable_id(Integer.parseInt(table_id)); Set<Entry<Food,Integer>> entrySet = m.entrySet(); //定义总价钱 int sum =0; for (Entry<Food, Integer> entry : entrySet) { Food food = entry.getKey(); Integer count = entry.getValue(); order.setId(food.getId()); sum += food.getPrice()*count; order.setOrderDate(new Date()); } order.setTotalPrice(sum); //创建订单详细对象 uri="/app/detail/clientCart.jsp"; return uri; }*/ } package com.xp.servlet; import java.io.IOException; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.xp.entity.DinnerTable; import com.xp.entity.Food; import com.xp.entity.OrderDetail; import com.xp.entity.Orders; import com.xp.utils.PageBean; public class OrderServlet extends BaseServlet { @Override public void init() throws ServletException { List<Orders> orders = ordersService.query(); List<OrderDetail> orderDetail = orderDetailService.query(); this.getServletContext().setAttribute("orders", orders); this.getServletContext().setAttribute("orderDetail", orderDetail); } //放入购物车 public Object putInCar(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); Object uri = null; Map<Food, Integer> map = new LinkedHashMap<Food, Integer>(); // 获取食物id String id = request.getParameter("food_id"); Food food = foodService.findById(Integer.parseInt(id)); //用于存储订单数据 Map<Food, Integer> m = (Map<Food, Integer>) session .getAttribute("foods"); if (m != null) { if (m.containsKey(food)) { Integer count = m.get(food); count++; m.put(food, count); } else { m.put(food, 1); } } else { map.put(food, 1); } if (m != null) { session.setAttribute("foods", m); } else { session.setAttribute("foods", map); } uri = "/app/detail/clientCart.jsp"; return uri; } //删除订单 public Object removeOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object uri = null; String id = request.getParameter("gid"); Food food = foodService.findById(Integer.parseInt(id)); HttpSession session = request.getSession(); //获取加入餐车时的食物数据 Map<Food, Integer> m = (Map<Food, Integer>) session .getAttribute("foods"); m.remove(food); session.setAttribute("foods", m); uri = "/app/detail/clientCart.jsp"; return uri; } public Object alterSorder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object uri = null; String id = request.getParameter("gid"); Food food = foodService.findById(Integer.parseInt(id)); // 获取修改狗的数量 String num = request.getParameter("snumber"); HttpSession session = request.getSession(); Map<Food, Integer> m = (Map<Food, Integer>) session .getAttribute("foods"); m.put(food, Integer.parseInt(num)); session.setAttribute("foods", m); uri = "/app/detail/clientCart.jsp"; return uri; } //下单的方法 public Object takeOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object uri = null; HttpSession session = request.getSession(); @SuppressWarnings("unchecked") Map<Food, Integer> m = (Map<Food, Integer>) session .getAttribute("foods"); String table_id = (String) session.getAttribute("table_id"); // 新建订单对象 Orders order = new Orders(); order.setTable_id(Integer.parseInt(table_id)); Set<Entry<Food, Integer>> entrySet = m.entrySet(); // 创建订单详细对象 OrderDetail detail = new OrderDetail(); // 定义总价钱 int sum = 0; int orderId = ordersService.getCount() + 1; for (Entry<Food, Integer> entry : entrySet) { Food food = entry.getKey(); Integer count = entry.getValue(); order.setId(food.getId()); sum += food.getPrice() * count; order.setOrderDate(new Date()); } order.setTotalPrice(sum); ordersService.add(order); for (Entry<Food, Integer> entry : entrySet) { Food food = entry.getKey(); Integer count = entry.getValue(); detail.setFood_id(food.getId()); detail.setOrderId(orderId); detail.setFoodCount(count); orderDetailService.add(detail); } findOrder(request, response); uri = "/app/detail/clientOrderList.jsp"; return uri; } public void findOrder(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Orders> orders = ordersService.query(); List<OrderDetail> orderDetail = orderDetailService.query(); this.getServletContext().setAttribute("orders", orders); this.getServletContext().setAttribute("orderDetail", orderDetail); } public Object getOrderDetail(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object uri = null; String id = request.getParameter("orderId"); List<OrderDetail> list = null; if (id != null && !id.isEmpty()) { list = orderDetailService.findByOrderId(Integer.parseInt(id)); } request.setAttribute("orderDetail", list); uri = request.getRequestDispatcher("/sys/order/orderDetail.jsp"); return uri; } // 后台结账的方法 public Object pay(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object uri = null; String oid = request.getParameter("orderId"); Orders o = new Orders(); o.setOrderStatus(1); o.setId(Integer.parseInt(oid)); ordersService.update(o); String tid = request.getParameter("tableId"); if (tid != null) { tableService.quitTable(Integer.parseInt(tid)); } findOrder(request, response); DinnerTable table = tableService.findById(Integer.parseInt(tid));// 用于后台点击结账时消除通知 @SuppressWarnings("unchecked") List<String> list = (List<String>) this.getServletContext() .getAttribute("tn"); if (list != null) { list.remove(table.getTableName()); } getOrderList(request, response); // 5. 跳转 uri = request.getRequestDispatcher("sys/order/orderList.jsp"); return uri; } // 前台呼叫结账的方法 public Object call(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object uri = null; HttpSession session = request.getSession(); String id = (String) session.getAttribute("table_id"); DinnerTable table = tableService.findById(Integer.parseInt(id)); String tableName = table.getTableName(); @SuppressWarnings("unchecked") List<String> tab = (List<String>) this.getServletContext() .getAttribute("tn"); if (tab == null) { tab = new ArrayList<String>(); } tab.add(tableName); this.getServletContext().setAttribute("tn", tab); List<DinnerTable> tables = tableService.query();// 更新前台首页的桌子 this.getServletContext().setAttribute("table", tables); uri = "/app/index.jsp"; return uri; } public Object getOrderList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Object uri = null; // 1. 获取“当前页”参数; (第一次访问当前页为null) String currPage = request.getParameter("currentPage"); // 判断 if (currPage == null || "".equals(currPage.trim())) { currPage = "1"; // 第一次访问,设置当前页为1; } // 转换 int currentPage = Integer.parseInt(currPage); // 2. 创建PageBean对象,设置当前页参数; 传入service方法参数 PageBean<Orders> pageBean = new PageBean<Orders>(); pageBean.setCurrentPage(currentPage); pageBean.setPageCount(6); // 3. 调用service ordersService.getAll(pageBean); // 【pageBean已经被dao填充了数据】 // 4. 保存pageBean对象,到request域中 request.setAttribute("pageBean", pageBean); // 5. 跳转 uri = request.getRequestDispatcher("sys/order/orderList.jsp"); return uri; } } Instance.properties # dao instance foodTypeDao = com.xp.dao.impl.FoodTypeDao dinnerTableDao =com.xp.dao.impl.DinnerTableDao foodDao = com.xp.dao.impl.FoodDao ordersDao=com.xp.dao.impl.OrdersDao orderDetailDao=com.xp.dao.impl.OrderDetailDao # service instance foodTypeService =com.xp.service.impl.FoodTypeService dinnerTableService=com.xp.service.impl.DinnerTableService foodService =com.xp.service.impl.FoodService ordersService=com.xp.service.impl.OrdersService orderDetailService=com.xp.service.impl.OrderDetailService package com.xp.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class BrowserFilter implements Filter{ @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String userAgent = request.getHeader("user-agent"); if(userAgent.contains("Firefox")){ chain.doFilter(request, response); }else if(userAgent.contains("Chrome")){ chain.doFilter(request, response); }else if(userAgent.contains(".NET")){ chain.doFilter(request, response); }else{ } } @Override public void destroy() { } } package com.xp.filter; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; public class EncodingRequest extends HttpServletRequestWrapper { private HttpServletRequest req; public EncodingRequest(HttpServletRequest request) { super(request); this.req = request; } public String getParameter(String name) { String value = req.getParameter(name); try { if(value!=null){ value = new String(value.getBytes("iso-8859-1"), "utf-8"); } } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } return value; } } package com.xp.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class EncodingFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); HttpServletRequest req = (HttpServletRequest) request; if(req.getMethod().equals("GET")) { EncodingRequest er = new EncodingRequest(req); chain.doFilter(er, response); } else if(req.getMethod().equals("POST")) { chain.doFilter(request, response); } } public void init(FilterConfig fConfig) throws ServletException { } } <?xml version="1.0" encoding="utf-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>hotel</display-name> <servlet> <servlet-name>DinnerTableServlet</servlet-name> <servlet-class>com.xp.servlet.DinnerTableServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet> <servlet-name>FoodTypeServlet</servlet-name> <servlet-class>com.xp.servlet.FoodTypeServlet</servlet-class> <load-on-startup>2</load-on-startup> </servlet> <servlet> <servlet-name>FoodServlet</servlet-name> <servlet-class>com.xp.servlet.FoodServlet</servlet-class> <load-on-startup>3</load-on-startup> </servlet> <servlet> <servlet-name>IndexServlet</servlet-name> <servlet-class>com.xp.servlet.IndexServlet</servlet-class> </servlet> <servlet> <servlet-name>OrderServlet</servlet-name> <servlet-class>com.xp.servlet.OrderServlet</servlet-class> <load-on-startup>4</load-on-startup> </servlet> <servlet-mapping> <servlet-name>DinnerTableServlet</servlet-name> <url-pattern>/table</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>FoodTypeServlet</servlet-name> <url-pattern>/foodType</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>FoodServlet</servlet-name> <url-pattern>/food</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>IndexServlet</servlet-name> <url-pattern>/index</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>OrderServlet</servlet-name> <url-pattern>/order</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/app/index.jsp</welcome-file> </welcome-file-list> <filter> <filter-name>encoding</filter-name> <filter-class>com.xp.filter.EncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>encoding</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>Browser</filter-name> <filter-class>com.xp.filter.BrowserFilter</filter-class> </filter> <filter-mapping> <filter-name>Browser</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>