更新菜单与更新桌号步骤完全一样,需要注意的是菜单名称含有中文,所以在servlet中将信息以xml形式发出时,应注意将其编码设定为gbk,如下:
<?xml version='1.0' encoding='gbk'?>
新建Menu数据实体类:
public class Menu { private int id; private int price; private int typeId; private String name; private String pic; private String remark; getters & setters .. }
在UpdateDao与UpdateDaoImpl中添加新方法getMenuList()获取菜单列表:
public interface UpdateDao { // 获得餐桌列表 public List<Table> getTableList(); // 获得菜单列表 public List<Menu> getMenuList(); }
@Override public List<Menu> getMenuList() { // jdbc连接数据库准备工作 DBUtil util = new DBUtil(); Connection conn = util.openConnection(); // 读出所有菜品信息准备工作 String sql = "select id, price, typeId, name, pic, remark from menutbl "; Statement statement = null; ResultSet rs = null; try { statement = conn.createStatement(); rs = statement.executeQuery(sql); // 新建list容纳所有桌号实体类对象 List<Menu> menulist = new ArrayList<Menu>(); while (rs.next()) { Menu menu = new Menu(); menu.setId(rs.getInt(1)); menu.setPrice(rs.getInt(2)); menu.setTypeId(rs.getInt(3)); menu.setName(rs.getString(4)); menu.setPic(rs.getString(5)); menu.setRemark(rs.getString(6)); menulist.add(menu); } // 别忘了返回list return menulist; } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rs != null) { rs.close(); rs = null; } if (statement != null) { statement.close(); statement = null; } if (conn != null) { conn.close(); conn = null; } } catch (SQLException e) { e.printStackTrace(); } } return null; }
然后是专门为更新菜单服务的UpdateMenuServlet:
public class UpdateMenuServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintWriter pw = new PrintWriter(resp.getOutputStream()); // 获取所有菜单信息列表 UpdateDao updateDao = new UpdateDaoImpl(); List<Menu> menuList = updateDao.getMenuList(); // 将所有信息以xml格式输出, 此处设定编码为gbk, 否则中文乱码 pw.println("<?xml version='1.0' encoding='gbk'?>"); pw.println("<menulist>"); for (int i = 0; i < menuList.size(); i++) { Menu menu = menuList.get(i); pw.println("<menu>"); pw.print("<id>"); pw.print(menu.getId()); pw.print("</id>"); pw.print("<price>"); pw.print(menu.getPrice()); pw.print("</price>"); pw.print("<typeId>"); pw.print(menu.getTypeId()); pw.print("</typeId>"); pw.print("<name>"); pw.print(menu.getName()); pw.print("</name>"); pw.print("<pic>"); pw.print(menu.getPic()); pw.print("</pic>"); pw.print("<remark>"); pw.print(menu.getRemark()); pw.print("</remark>"); pw.println("</menu>"); } pw.println("</menulist>"); pw.flush(); pw.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
注册servlet:
<servlet> <servlet-name>UpdateMenuServlet</servlet-name> <servlet-class>com.moka.servlet.UpdateMenuServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UpdateMenuServlet</servlet-name> <url-pattern>/servlet/UpdateMenuServlet</url-pattern> </servlet-mapping>