自定义MVC的增删改查

简介: 自定义MVC的增删改查
1.将框架打成jar包,然后导入新工程,并且把框架的依赖jar包导入进去

二.实现增删改查

1.编写实体类、dao类、

1.1 实体类
package com.zhanghao.entity;
public class Book {
  private int bid;
  private String bname;
  private float price;
  public int getBid() {
    return bid;
  }
  public void setBid(int bid) {
    this.bid = bid;
  }
  public String getBname() {
    return bname;
  }
  public void setBname(String bname) {
    this.bname = bname;
  }
  public float getPrice() {
    return price;
  }
  public void setPrice(float price) {
    this.price = price;
  }
  @Override
  public String toString() {
    return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
  }
  public Book(int bid, String bname, float price) {
    super();
    this.bid = bid;
    this.bname = bname;
    this.price = price;
  }
  public Book() {
    super();
  }
} 

dao:通用的增删改查

package com.zhanghao.util;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.zhanghao.util.DBAccess;
import com.zhanghao.util.PageBean;
import com.zhanghao.util.StringUtils;
/**
 * 所有Dao层的父类
 *  BookDao
 *  UserDao
 *  OrderDao
 *  ...
 * @author Administrator
 *
 * @param <T>
 */
public class BaseDao<T> {
  /**
   * 通用的增删改方法
   * @param book
   * @throws Exception
   */
  public void executeUpdate(String sql, T t, String[] attrs) throws Exception {
//    String[] attrs = new String[] {"bid", "bname", "price"};
    Connection con = DBAccess.getConnection();
    PreparedStatement pst = con.prepareStatement(sql);
//    pst.setObject(1, book.getBid());
//    pst.setObject(2, book.getBname());
//    pst.setObject(3, book.getPrice());
    /*
     * 思路:
     *  1.从传进来的t中读取属性值
     *  2.往预定义对象中设置了值
     *  
     *  t->book
     *  f->bid
     */
    for (int i = 0; i < attrs.length; i++) {
      Field f = t.getClass().getDeclaredField(attrs[i]);
      f.setAccessible(true);
      pst.setObject(i+1, f.get(t));
    }
    pst.executeUpdate();
  }
  /**
   * 通用分页查询
   * @param sql
   * @param clz
   * @return
   * @throws Exception
   */
  public List<T> executeQuery(String sql,Class<T> clz,PageBean pageBean) throws Exception{
    List<T> list = new ArrayList<T>();
    Connection con = DBAccess.getConnection();;
    PreparedStatement pst = null;
    ResultSet rs = null;
    /*
     * 是否需要分页?
     *  无需分页(项目中的下拉框,查询条件教员下拉框,无须分页)  
     *  必须分页(项目中列表类需求、订单列表、商品列表、学生列表...)
     */
    if(pageBean != null && pageBean.isPagination()) {
//      必须分页(列表需求)
      String countSQL = getCountSQL(sql);
      pst = con.prepareStatement(countSQL);
      rs = pst.executeQuery();
      if(rs.next()) {
        pageBean.setTotal(String.valueOf(rs.getObject(1)));
      }
//      挪动到下面,是因为最后才处理返回的结果集
//      -- sql=SELECT * FROM t_mvc_book WHERE bname like '%圣墟%'
//      -- pageSql=sql limit (page-1)*rows,rows   对应某一页的数据
//      -- countSql=select count(1) from (sql) t  符合条件的总记录数
      String pageSQL = getPageSQL(sql,pageBean);//符合条件的某一页数据
      pst = con.prepareStatement(pageSQL);
      rs = pst.executeQuery();
    }else {
//      不分页(select需求)
      pst = con.prepareStatement(sql);//符合条件的所有数据
      rs = pst.executeQuery();
    }
    while (rs.next()) {
      T t = clz.newInstance();
      Field[] fields = clz.getDeclaredFields();
      for (Field f : fields) {
        f.setAccessible(true);
        f.set(t, rs.getObject(f.getName()));
      }
      list.add(t);
    }
    return list;
  }
  /**
   * 将原生SQL转换成符合条件的总记录数countSQL
   * @param sql
   * @return
   */
  private String getCountSQL(String sql) {
//    -- countSql=select count(1) from (sql) t  符合条件的总记录数
    return "select count(1) from ("+sql+") t";
  }
  /**
   * 将原生SQL转换成pageSQL
   * @param sql
   * @param pageBean
   * @return
   */
  private String getPageSQL(String sql,PageBean pageBean) {
//    (this.page - 1) * this.rows
//    pageSql=sql limit (page-1)*rows,rows
    return sql + " limit "+ pageBean.getStartIndex() +","+pageBean.getRows();
  }
}

Doa分页查询和通用增删改:

package com.zhanghao.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import com.zhanghao.entity.Book;
import com.zhanghao.util.BaseDao;
import com.zhanghao.util.DBAccess;
import com.zhanghao.util.PageBean;
import com.zhanghao.util.StringUtils;
public class BookDao extends BaseDao<Book>{
  /*
   * public void add(Book book) throws Exception {
    String sql = "insert into t_mvc_book values(?,?,?)";
    Connection con = DBAccess.getConnection();
    PreparedStatement pst = con.prepareStatement(sql);
    pst.setObject(1, book.getBid());
    pst.setObject(2, book.getBname());
    pst.setObject(3, book.getPrice());
    pst.executeUpdate();
    }
    增删改查的通用套路
    1.建立链接
    2.预定义对象PreparedStatement
    3.设置占位符的?的值
    4.pst.executeUpdate();
    1.
   */
  public void add(Book book) throws Exception {
    String sql = "insert into t_mvc_book values(?,?,?)";
    super.executeUpdate(sql, book, new String[] {"bid","bname","price"});
  }
  public void edit(Book book) throws Exception {
    String sql = "update t_mvc_book set bname = ?, price = ? where bid = ?";
    super.executeUpdate(sql, book, new String[] {"bname","price","bid"});
  }
  public void delete(Book book) throws Exception {
    String sql = "delete from t_mvc_book where bid = ?";
    super.executeUpdate(sql, book, new String[] {"bid"});
  }
  public List<Book> list(Book book,PageBean pageBean) throws Exception {
    String sql = "select * from t_mvc_book where 1=1 ";
    String bname = book.getBname();
    if(StringUtils.isNotBlank(bname)) {
      sql += " and bname like '%"+bname+"%'";
    }
    return super.executeQuery(sql, Book.class, pageBean);
  }
  public static void main(String[] args) throws Exception {
    Book b = new Book();
    b.setBid(2323);
    b.setBname("测试www");
    b.setPrice(231f);
    BookDao bookDao = new BookDao();
//    bookDao.delete(b);
//    bookDao.add(b);
    bookDao.edit(b);
  }
  public List<Book> list(String string, PageBean pageBean) {
    // TODO Auto-generated method stub
    return null;
  }
}

后台代码:

package com.zhanghao.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhanghao.dao.BookDao;
import com.zhanghao.entity.Book;
import com.zhanghao.util.PageBean;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriven;
public class BookAction extends ActionSupport implements ModelDriven<Book>{
  private Book book = new Book();
  private BookDao bookDao = new BookDao();
  public Book getModel() {
    return book;
  }
  /*
   * 增删改最终都要跳回查询界面
   * 分析增删改查一共有多少结果集的配置
   * 查询:BookList.jsp    返回值:list
   * 增删改确定:book.action?methodName=list    返回值:toList
   * 增加修改跳转对应界面:bookEdit.jsp      返回值:toEdit
   */
  public String add(HttpServletRequest req, HttpServletResponse resp) {
    try {
      bookDao.add(book);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "toList";
  }
  public String list(HttpServletRequest req, HttpServletResponse resp) {
    try {
      PageBean pageBean = new PageBean();
      pageBean.setRequest(req);
      List<Book> list = bookDao.list("book", pageBean);
      req.setAttribute("books", list);
      req.setAttribute("pageBean", pageBean);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "list";
  }
  public String delete(HttpServletRequest req, HttpServletResponse resp) {
    try {
      bookDao.delete(book);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "toList";
  }
  public String edit(HttpServletRequest req, HttpServletResponse resp) {
    try {
      bookDao.edit(book);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "toList";
  }
  /**
   * 跳转到新增修改页面
   * @param req
   * @param resp
   * @return
   */
  public String toEdit(HttpServletRequest req, HttpServletResponse resp) {
    try {
      /*
       * 如果是跳转修改页面,那么需要做bid条件的精准查询
       */
      if(book.getBid() != 0) {
        List<Book> list = bookDao.list(book, null);
        req.setAttribute("b", list.get(0));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "toEdit";
  }
}

前台页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link
  href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
  rel="stylesheet">
<script
  src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
<title>书籍新增/修改</title>
</head>
<body>
  <form class="form-inline"
    action="${pageContext.request.contextPath }/book.action?methodName=${empty b ? 'add' : 'edit'}" method="post">
    书籍ID:<input type="text" name="bid" value="${b.bid }"><br>
    书籍名称:<input type="text" name="bname" value="${b.bname }"><br>
    书籍价格:<input type="text" name="price" value="${b.price }"><br>
    <input type="submit">
  </form>
</body>
</html>


目录
相关文章
|
2月前
|
前端开发 Java 数据库
springBoot:template engine&自定义一个mvc&后端给前端传数据&增删改查 (三)
本文介绍了如何自定义一个 MVC 框架,包括后端向前端传递数据、前后端代理配置、实现增删改查功能以及分页查询。详细展示了代码示例,从配置文件到控制器、服务层和数据访问层的实现,帮助开发者快速理解和应用。
|
7月前
|
前端开发 Java 网络安全
ssh(Spring+Spring mvc+hibernate)简单增删改查案例
ssh(Spring+Spring mvc+hibernate)简单增删改查案例
|
7月前
|
前端开发 Java
自定义mvc的增删改查
自定义mvc的增删改查
69 0
|
7月前
|
XML 前端开发 数据格式
自定义MVC引用XML配置文件实现
自定义MVC引用XML配置文件实现
71 0
|
7月前
|
设计模式 前端开发 搜索推荐
自定义mvc框架
自定义mvc框架
74 0
|
设计模式 前端开发
自定义mvc
自定义mvc
56 0
|
前端开发 Java 程序员
Spring-MVC的crud增删改查--详细讲解
Spring-MVC的crud增删改查--详细讲解
|
XML 前端开发 数据格式
自定义MVC超详细易懂----增删改查
自定义MVC超详细易懂----增删改查
114 0
|
4月前
|
开发框架 前端开发 .NET
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
56 0
|
7月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
212 0