更新功能模块的功能是实现客户端的数据与服务器端数据的同步,如果服务器端添了桌台,或者添了新的菜品,我们可以直接使用更新功能把最新的数据同步到客户端的Sqlite对应的表中。此功能涉及2个表的更新:tabletbl和menutbl。本篇先讨论tabletbl更新的服务器端编写。
首先建立table表的实体类:
public class Table { // 桌号 private int id; // 数量 private int num; // 是否有人标记 private int flag; // 描述 private String description; getters & setters .. }
然后新建更新的数据访问对象UpdateDao与UpdateDaoImpl:
public interface UpdateDao { // 获得餐桌列表 public List<Table> getTableList(); }
public class UpdateDaoImpl implements UpdateDao { @Override public List<Table> getTableList() { // jdbc连接数据库准备工作 DBUtil util = new DBUtil(); Connection conn = util.openConnection(); // 读出所有桌号信息准备工作 String sql = "select id, num, flag, description from tabletbl "; Statement statement = null; ResultSet rs = null; try { statement = conn.createStatement(); rs = statement.executeQuery(sql); // 新建list容纳所有桌号实体类对象 List<Table> tableList = new ArrayList<Table>(); while (rs.next()) { // table 要放在while循环内每次新建, 否则list中结果始终会是最后一个桌号 Table table = new Table(); table.setId(rs.getInt(1)); table.setNum(rs.getInt(2)); table.setFlag(rs.getInt(3)); table.setDescription(rs.getString(4)); tableList.add(table); } // 别忘了返回list return tableList; } 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; } }
然后是专供桌号更新操作的UpdateTableServlet:
public class UpdateTableServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html"); PrintStream pw = new PrintStream(resp.getOutputStream()); // 获取所有桌号信息列表 UpdateDao updateDao = new UpdateDaoImpl(); List<Table> tableList = updateDao.getTableList(); // 将所有信息以xml格式输出 pw.println("<?xml version='1.0' encoding='UTF-8'?>"); pw.println("<tablelist>"); for (int i = 0; i < tableList.size(); i++) { Table table = tableList.get(i); pw.println("<table>"); pw.print("<id>"); pw.print(table.getId()); pw.print("</id>"); pw.print("<num>"); pw.print(table.getNum()); pw.print("</num>"); pw.print("<description>"); pw.print(table.getDescription()); pw.print("</description>"); pw.println("</table>"); } pw.println("</tablelist>"); pw.flush(); pw.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
最后注册servlet:
<servlet> <servlet-name>UpdateTableServlet</servlet-name> <servlet-class>com.moka.servlet.UpdateTableServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UpdateTableServlet</servlet-name> <url-pattern>/servlet/UpdateTableServlet</url-pattern> </servlet-mapping>