ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

浅谈MVC+小例子

2021-02-23 13:05:29  阅读:160  来源: 互联网

标签:hero 浅谈 int MVC hp id 例子 public name


谈谈MVC

一、个人理解

​ 如果我们将数据库增删改的操作代码、业务代码、界面的html脚本代码都写在Servlet文件中,这样Servlet代码将会变得臃肿,可读性非常差,维护的时会相当麻烦。为此我们需要需找一个架构方法让代码的结构更清晰,更容易维护,MVC就是解决该问题的架构模式之一。

​ MVC是三个单词首字母的首拼,分别是Model(模型)、View(视图)和Contorller(控制)。该结构可以简单的看成三层

1)最上面的一层,是直接面向最终用户的"视图层"(View)。它是提供给用户的操作界面,是程序的外壳。

2)中间的一层,就是"控制层"(Controller),它负责根据用户从"视图层"输入的指令,选取"数据层"中的数据,然后对其进行相应的操作,产生最终结果。

3)最底下的一层,是核心的"数据层"(Model),也就是程序需要操作的数据或信息。

二、使用MVC思想实现查询功能

1、实体类Hero

public class Hero{
    public int id;
    public String name;
    public float hp;
    public int damage;
    public int getId(){return id;}
    public String getName(){return name;}
    public float getHp(){return hp;}
    public int getDamage(){return damage;}
    public void setId(int id){this.id=id;}
    public void setName(String name){this.name=name;}
    public void setHp(float hp){this.hp=hp;}
    public void setDamage(int damage){this.damage=damage;}
}

2、HeroDao

public class HeroDAO {
   
    public HeroDAO() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
   
    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/how2java?characterEncoding=UTF-8", "root",
                "admin");
    }
   
    public int getTotal() {
        int total = 0;
        try (Connection c = getConnection(); Statement s = c.createStatement();) {
   
            String sql = "select count(*) from hero";
   
            ResultSet rs = s.executeQuery(sql);
            while (rs.next()) {
                total = rs.getInt(1);
            }
   
            System.out.println("total:" + total);
   
        } catch (SQLException e) {
   
            e.printStackTrace();
        }
        return total;
    }
   
    public void add(Hero hero) {
   
        String sql = "insert into hero values(null,?,?,?)";
        try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) {
   
            ps.setString(1, hero.name);
            ps.setFloat(2, hero.hp);
            ps.setInt(3, hero.damage);
   
            ps.execute();
   
            ResultSet rs = ps.getGeneratedKeys();
            if (rs.next()) {
                int id = rs.getInt(1);
                hero.id = id;
            }
        } catch (SQLException e) {
   
            e.printStackTrace();
        }
    }
   
    public void update(Hero hero) {
   
        String sql = "update hero set name= ?, hp = ? , damage = ? where id = ?";
        try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) {
   
            ps.setString(1, hero.name);
            ps.setFloat(2, hero.hp);
            ps.setInt(3, hero.damage);
            ps.setInt(4, hero.id);
   
            ps.execute();
   
        } catch (SQLException e) {
   
            e.printStackTrace();
        }
   
    }
   
    public void delete(int id) {
   
        try (Connection c = getConnection(); Statement s = c.createStatement();) {
   
            String sql = "delete from hero where id = " + id;
   
            s.execute(sql);
   
        } catch (SQLException e) {
   
            e.printStackTrace();
        }
    }
   
    public Hero get(int id) {
        Hero hero = null;
   
        try (Connection c = getConnection(); Statement s = c.createStatement();) {
   
            String sql = "select * from hero where id = " + id;
   
            ResultSet rs = s.executeQuery(sql);
   
            if (rs.next()) {
                hero = new Hero();
                String name = rs.getString(2);
                float hp = rs.getFloat("hp");
                int damage = rs.getInt(4);
                hero.name = name;
                hero.hp = hp;
                hero.damage = damage;
                hero.id = id;
            }
   
        } catch (SQLException e) {
   
            e.printStackTrace();
        }
        return hero;
    }
   
    public List<Hero> list() {
        return list(0, Short.MAX_VALUE);
    }
   
    public List<Hero> list(int start, int count) {
        List<Hero> heros = new ArrayList<Hero>();
   
        String sql = "select * from hero order by id desc limit ?,? ";
   
        try (Connection c = getConnection(); PreparedStatement ps = c.prepareStatement(sql);) {
   
            ps.setInt(1, start);
            ps.setInt(2, count);
   
            ResultSet rs = ps.executeQuery();
   
            while (rs.next()) {
                Hero hero = new Hero();
                int id = rs.getInt(1);
                String name = rs.getString(2);
                float hp = rs.getFloat("hp");
                int damage = rs.getInt(4);
                hero.id = id;
                hero.name = name;
                hero.hp = hp;
                hero.damage = damage;
                heros.add(hero);
            }
        } catch (SQLException e) {
   
            e.printStackTrace();
        }
        return heros;
    }
   
}

3、HeroServlet

public class HeroListServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            List<Hero> heros=new HeroDao().list();
            req.setAttribute("heros",heros);
            req.getRequestDispatcher("listHero.jsp").forward(req, resp);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
//配置web.xml

4、listHero.jsp

<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%>
<%@page isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table align="center" border="1" cellspacing="0">
    <tr>
        <td>id</td>
        <td>name</td>
        <td>hp</td>
        <td>damage</td>
        <td>edit</td>
        <td>delete</td>
    </tr>
    <c:forEach items="${heros}" var="hero" varStatus="st">
        <tr>
            <td>${hero.id}</td>
            <td>${hero.name}</td>
            <td>${hero.hp}</td>
            <td>${hero.damage}</td>
            <td><a href="editHero?id=${hero.id}">edit</a></td>
            <td><a href="deleteHero?id=${hero.id}">delete</a></td>
        </tr>
    </c:forEach>
    <tr></tr>
</table>
</body>
</html>

效果:

三、使用mvc思想实现分页功能

1、修改HeroServlet

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            int total=new HeroDao().total();
            int start=0;
            int count=5;
            try {
                start = Integer.parseInt(req.getParameter("start"));
            } catch (NumberFormatException e) {
                // 当浏览器没有传参数start时
            }
            int next = start + count;
            int pre=start-count;
            int last;
            if (0 == total % count)
  			last = total - count;
            else 
                last=total-tatal%count;
            //第一页和最后一页的边界处理
             pre = pre < 0 ? 0 : pre;
        next = next > last ? last : next;
            List<Hero> heros=new HeroDao().list(start,count);
            req.setAttribute("next", next); 
            req.setAttribute("pre", pre);
            req.setAttribute("last", last); 
            req.setAttribute("heros",heros);
            req.getRequestDispatcher("listHero.jsp").forward(req, resp);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

2、修改listHero.jsp

添加了首页、上一页,下一页,末页的超链接标签。

<%--
  Created by IntelliJ IDEA.
  User: QY
  Date: 2021/2/23
  Time: 11:11
  To change this template use File | Settings | File Templates.
--%>

<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" import="java.util.*"%>
<%@page isELIgnored="false" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table align="center" border="1" cellspacing="0">
    <tr>
        <td>id</td>
        <td>name</td>
        <td>hp</td>
        <td>damage</td>
        <td>edit</td>
        <td>delete</td>
    </tr>
    <c:forEach items="${heros}" var="hero" varStatus="st">
        <tr>
            <td>${hero.id}</td>
            <td>${hero.name}</td>
            <td>${hero.hp}</td>
            <td>${hero.damage}</td>
            <td><a href="editHero?id=${hero.id}">edit</a></td>
            <td><a href="deleteHero?id=${hero.id}">delete</a></td>
        </tr>
    </c:forEach>
    <tr>
        <td colspan="6" align="center"><a href="?start=0">[首页]</a>
        <a href="?start=${pre}">[上一页]</a>
        <a href="?start=${next}">[下一页]</a>
        <a href="?start=${last}">[末页]</a>
        </td>
    </tr>
</table>
</body>
</html>

效果:

标签:hero,浅谈,int,MVC,hp,id,例子,public,name
来源: https://www.cnblogs.com/feixiong1/p/14435404.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有