• MVC系列教材 (二)- 结合Servlet和JSP 实现查询功能


    使用MVC的思想,结合Servlet和JSP进行查询操作

    步骤1:实体类Hero
    步骤2:HeroDAO
    步骤3:HeroListServlet
    步骤4:web.xml
    步骤5:listHero.jsp

    步骤 1 : 实体类Hero

    package bean;

      

    public class Hero {

      

        public int id;

        public String name;

        public float hp;

        public int damage;

        public int getId() {

            return id;

        }

        public void setId(int id) {

            this.id = id;

        }

        public String getName() {

            return name;

        }

        public void setName(String name) {

            this.name = name;

        }

        public float getHp() {

            return hp;

        }

        public void setHp(float hp) {

            this.hp = hp;

        }

        public int getDamage() {

            return damage;

        }

        public void setDamage(int damage) {

            this.damage = damage;

        }

          

    }

    步骤 2 : HeroDAO

    使用在前面教程中用到的HeroDAO用于从数据库查询数据

    package dao;

       

    import java.sql.Connection;

    import java.sql.DriverManager;

    import java.sql.PreparedStatement;

    import java.sql.ResultSet;

    import java.sql.SQLException;

    import java.sql.Statement;

    import java.util.ArrayList;

    import java.util.List;

      

    import bean.Hero;

       

    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 : HeroListServlet

    作为控制器的HeroListServlet,其作用就是通过dao获取所有的heros对象,然后放在request中,跳转到listHero.jsp

    package 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 bean.Hero;

    import dao.HeroDAO;

    public class HeroListServlet extends HttpServlet {

        protected void service(HttpServletRequest request, HttpServletResponse response)

                throws ServletException, IOException {

        List<Hero> heros = new HeroDAO().list();

            request.setAttribute("heros", heros);

            request.getRequestDispatcher("listHero.jsp").forward(request, response);

        }

    }

    步骤 4 : web.xml

    <web-app>

        <servlet>

            <servlet-name>HeroListServlet</servlet-name>

            <servlet-class>servlet.HeroListServlet</servlet-class>

        </servlet>

        <servlet-mapping>

            <servlet-name>HeroListServlet</servlet-name>

            <url-pattern>/listHero</url-pattern>

        </servlet-mapping>

    </web-app>

    步骤 5 : listHero.jsp

    作为视图的listHero.jsp,其作用就是把控制器传过来的数据显示出来

    listHero.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"

        pageEncoding="UTF-8" import="java.util.*"%>

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

    <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>

    </table>


    更多内容,点击了解: https://how2j.cn/k/mvc/mvc-query/585.html

  • 相关阅读:
    JLOI2014 聪明的燕姿【搜索-细节】
    JOI2014 バス通学【思维】
    【线段树】USACO 08FEB Hotel G
    USACO20FEB Equilateral Triangles P【思维-曼哈顿距离-切比雪夫距离】
    USACO 2019DEC Milk Visits
    【规律】ABC179 E Sequence Sum
    【前缀和优化dp】ABC179 D Leaping Tak
    SPOJ2916 GSS5-Can you answer these queries V【线段树】
    SPOJ1557 GSS2-Can you answer these queries II【线段树】
    推荐系统之余弦相似度的Spark实现
  • 原文地址:https://www.cnblogs.com/Lanht/p/12789444.html
Copyright © 2020-2023  润新知