1 文件结构

  1. dao包下是实体类与数据库的接口
  2. model包下都是bean,实体模型
  3. servlet包下都是Servlet子类

图片.png

2 bean与dao

2.1 bean与dao的关系

  1. bean,对每个属性实现了get和set的类
  2. dao,(Data Access Object) 数据访问对象是一个面向对象的数据库接口
  3. 一个bean对应一个dao

    2.2 bean

  1. package model;
  2. public class Hero {
  3. // 实体类,又称模型类,bean
  4. public int id;
  5. public String name;
  6. public float hp;
  7. public int damage;
  8. public int getId() {
  9. return id;
  10. }
  11. public void setId(int id) {
  12. this.id = id;
  13. }
  14. public String getName() {
  15. return name;
  16. }
  17. public void setName(String name) {
  18. this.name = name;
  19. }
  20. public float getHp() {
  21. return hp;
  22. }
  23. public void setHp(float hp) {
  24. this.hp = hp;
  25. }
  26. public int getDamage() {
  27. return damage;
  28. }
  29. public void setDamage(int damage) {
  30. this.damage = damage;
  31. }
  32. }

2.3 dao

  1. public class HeroDao {
  2. // DAO
  3. // (Data Access Object) 数据访问对象是一个面向对象的数据库接口
  4. // 构造函数加载数据库驱动
  5. public HeroDao() {
  6. // 通过反射调用com.mysql.jdbc.Driver的静态域代码
  7. try {
  8. Class.forName("com.mysql.jdbc.Driver");
  9. } catch (ClassNotFoundException e) {
  10. System.out.println("数据库加载失败");
  11. e.printStackTrace();
  12. }
  13. }
  14. // 连接数据库
  15. public Connection getConnection() throws SQLException {
  16. return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8", "root",
  17. "HDD740409");
  18. }
  19. // 获得记录总个数
  20. public int getTotal() {
  21. int total = 0;
  22. try (Connection c = getConnection(); Statement s = c.createStatement();) {
  23. String sql = "select count(*) from hero";
  24. ResultSet rs = s.executeQuery(sql);
  25. while (rs.next()) {
  26. total = rs.getInt(1);
  27. }
  28. System.out.println("total:" + total);
  29. } catch (SQLException e) {
  30. e.printStackTrace();
  31. }
  32. return total;
  33. }
  34. // 通过预处理语句对数据表单条记录增改删查
  35. public void add(Hero hero) {
  36. String sql = "insert into hero values(null,?,?,?)";
  37. try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) {
  38. ps.setString(1, hero.name);
  39. ps.setFloat(2, hero.hp);
  40. ps.setInt(3, hero.damage);
  41. ps.execute();
  42. ResultSet rs = ps.getGeneratedKeys();
  43. if (rs.next()) {
  44. int id = rs.getInt(1);
  45. hero.id = id;
  46. }
  47. } catch (SQLException e) {
  48. e.printStackTrace();
  49. }
  50. }
  51. public void update(Hero hero) {
  52. String sql = "update hero set name= ?, hp = ? , damage = ? where id = ?";
  53. try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) {
  54. ps.setString(1, hero.name);
  55. ps.setFloat(2, hero.hp);
  56. ps.setInt(3, hero.damage);
  57. ps.setInt(4, hero.id);
  58. ps.execute();
  59. } catch (SQLException e) {
  60. e.printStackTrace();
  61. }
  62. }
  63. public void delete(int id) {
  64. try (Connection c = getConnection(); Statement s = c.createStatement();) {
  65. String sql = "delete from hero where id = " + id;
  66. s.execute(sql);
  67. } catch (SQLException e) {
  68. e.printStackTrace();
  69. }
  70. }
  71. public Hero get(int id) {
  72. Hero hero = null;
  73. try (Connection c = getConnection(); Statement s = c.createStatement();) {
  74. String sql = "select * from hero where id = " + id;
  75. ResultSet rs = s.executeQuery(sql);
  76. if (rs.next()) {
  77. hero = new Hero();
  78. String name = rs.getString(2);
  79. float hp = rs.getFloat("hp");
  80. int damage = rs.getInt(4);
  81. hero.name = name;
  82. hero.hp = hp;
  83. hero.damage = damage;
  84. hero.id = id;
  85. }
  86. } catch (SQLException e) {
  87. e.printStackTrace();
  88. }
  89. return hero;
  90. }
  91. // 显示所有记录
  92. public List<Hero> list() {
  93. return list(0, this.getTotal());
  94. }
  95. // 显示指定开头,数量的记录,用limit关键字
  96. public List<Hero> list(int start, int count) {
  97. List<Hero> heros = new ArrayList<Hero>();
  98. String sql = "select * from hero order by id ASC limit ?,? ";
  99. try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) {
  100. ps.setInt(1, start);
  101. ps.setInt(2, count);
  102. ResultSet rs = ps.executeQuery();
  103. while (rs.next()) {
  104. Hero hero = new Hero();
  105. int id = rs.getInt(1);
  106. String name = rs.getString(2);
  107. float hp = rs.getFloat("hp");
  108. int damage = rs.getInt(4);
  109. hero.id = id;
  110. hero.name = name;
  111. hero.hp = hp;
  112. hero.damage = damage;
  113. heros.add(hero);
  114. }
  115. } catch (SQLException e) {
  116. e.printStackTrace();
  117. }
  118. return heros;
  119. }
  120. }

2.4 SQL脚本

  1. use how2java;
  2. DROP TABLE IF EXISTS `hero`;
  3. CREATE TABLE `hero` (
  4. `id` int(11) NOT NULL AUTO_INCREMENT,
  5. `name` varchar(30) DEFAULT NULL,
  6. `hp` float DEFAULT NULL,
  7. `damage` int(11) DEFAULT NULL,
  8. PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
  10. select * from hero;

3 Servlet类

3.1 查

留下来一堆超链接指向其他Servlet或静态页面,分别指向

  1. 增加
  2. 删除
  3. 编辑

页面,代码

  1. public class HeroList extends HttpServlet {
  2. protected void service(HttpServletRequest request, HttpServletResponse response)
  3. throws ServletException, IOException {
  4. response.setContentType("text/html; charset=UTF-8");
  5. // 获得所有Hero
  6. List<Hero> heros = new HeroDao().list();
  7. // 可变字符串,利用字符串拼接实现数据内容填充
  8. StringBuffer sb = new StringBuffer();
  9. // 表格头部
  10. sb.append("<table align='center' border='1' cellspacing='0'>\r\n");
  11. sb.append("<tr><td>id</td><td>name</td><td>hp</td><td>damage</td><td>delete</td><td>edit</td></tr>\r\n");
  12. // 指定行元素格式
  13. String trFormat = "<tr><td>%d</td><td>%s</td><td>%f</td><td>%d</td><td><a href='deletehero?id=%d'>delete</a></td><td><a href='edithero?id=%d'>edit</a></td></tr>\r\n";
  14. for (Hero hero : heros) {
  15. // 按照指定行元素格式添加数据
  16. String tr = String.format(trFormat, hero.getId(), hero.getName(), hero.getHp(), hero.getDamage(),
  17. hero.getId(),hero.getId());
  18. sb.append(tr);
  19. }
  20. sb.append("<tr><td colspan=\"6\" style=\"text-align:center\"><a href=\"addhero.html\">新增</a></td></tr>\r\n");
  21. sb.append("</table>");
  22. response.getWriter().write(sb.toString());
  23. }
  24. }

3.2 增

  1. 一个静态页面图片.png
  2. 实现增加功能的Servlet
  1. public class AddHero extends HttpServlet {
  2. //根据提交过来的添加条目
  3. protected void service(HttpServletRequest request, HttpServletResponse response)
  4. throws ServletException, IOException {
  5. request.setCharacterEncoding("UTF-8");
  6. //创建一个新的实体
  7. Hero hero = new Hero();
  8. hero.setName(request.getParameter("name"));
  9. hero.setHp(Float.parseFloat(request.getParameter("hp")));
  10. hero.setDamage(Integer.parseInt(request.getParameter("damage")));
  11. new HeroDao().add(hero);
  12. //这个url不显示页面,而是用客户端跳转的方式跳转到展示页面
  13. response.sendRedirect("herolist");
  14. }
  15. }

3.3 删

  1. public class DeleteHero extends HttpServlet{
  2. // 根据url中的参数部分删除指定id的条目
  3. protected void service(HttpServletRequest request, HttpServletResponse response)
  4. throws ServletException, IOException {
  5. //获取查询字符串中的参数id
  6. int id = Integer.parseInt(request.getParameter("id"));
  7. new HeroDao().delete(id);
  8. //客户端跳转到展示页面
  9. response.sendRedirect("herolist");
  10. }
  11. }

3.4 改

  1. 修改内容的Servlet,根据传过来的id显示待修改的条目信息。等待修改。
  1. public class EditHero extends HttpServlet {
  2. protected void service(HttpServletRequest request, HttpServletResponse response)
  3. throws ServletException, IOException {
  4. // 根据查询字符串中的id查询该条目的信息,并且可以修改
  5. int id = Integer.parseInt(request.getParameter("id"));
  6. Hero hero = new HeroDao().get(id);
  7. StringBuffer format = new StringBuffer();
  8. response.setContentType("text/html; charset=UTF-8");
  9. format.append("<!DOCTYPE html>");
  10. format.append("<form action='updatehero' method='post'>");
  11. format.append("名字 : <input type='text' name='name' value='%s' > <br>");
  12. format.append("血量 : <input type='text' name='hp' value='%f' > <br>");
  13. format.append("伤害: <input type='text' name='damage' value='%d' > <br>");
  14. format.append("<input type='hidden' name='id' value='%d'>");
  15. format.append("<input type='submit' value='更新'>");
  16. format.append("</form>");
  17. String html = String.format(format.toString(), hero.getName(), hero.getHp(), hero.getDamage(), hero.getId());
  18. response.getWriter().write(html);
  19. }
  20. }
  1. 把修改提交到具体的功能页面更新。
  1. public class UpdateHero extends HttpServlet {
  2. protected void service(HttpServletRequest request, HttpServletResponse response)
  3. throws ServletException, IOException {
  4. // 根据post表单,把修改同步到数据库上
  5. request.setCharacterEncoding("UTF-8");
  6. Hero hero = new Hero();
  7. hero.setId(Integer.parseInt(request.getParameter("id")));
  8. hero.setName(request.getParameter("name"));
  9. hero.setHp(Float.parseFloat(request.getParameter("hp")));
  10. hero.setDamage(Integer.parseInt(request.getParameter("damage")));
  11. new HeroDao().update(hero);
  12. response.sendRedirect("herolist");
  13. }
  14. }

4 总结

4.1 与数据库相关的文件组成

  1. bean包
  2. model包
  3. servlet包

    4.2 对url新理解

    url不一定要显示页面,url的作用是实现某个功能的映射,可以实现完这个功能之后跳转到其他url。例如上面的AddHero、DeltetHero、UpdateHero都是实现功能之后跳转到主页,