自定义mvc三(增删改查)

目标 :   

    完成t_mvc_book表的增删改查
    1、通用分页的jar、自定义mvc框架、自定义标签
    导入jar、导入之前写好的pageTag、自定义mvc.xml
    2、dao层 通用的增删改方法
    3、web层
    mvc.xml进行配置
    4、jsp

导入jar包:

工具类:

1、通用的增删改方法定义

BookDao.java

package com.huang.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import com.huang.entity.Book;
import com.huang.util.BaseDao;
import com.huang.util.DBAccess;
import com.huang.util.PageBean;
import com.huang.util.StringUtils;

public class BookDao extends BaseDao<Book> {

    public List<Book> list(Book book,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException{
        String sql="select * from t_mvc_book where true";
        String bname=book.getBname();
        int bid=book.getBid();
        if(StringUtils.isNotBlank(bname)) {
            sql+="and bname like '%"+bname+"%'";
        }
        if(bid !=0) {
            sql+="and bid="+bid;
        }
        return super.executeQuery(sql, Book.class, pageBean);
    }
    
    
    /**
     * 修改
     * @param book
     * @return
     * @throws SQLException
     * @throws NoSuchFieldException
     * @throws SecurityException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public int edit (Book book) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
        String sql="update t_mvc_book set bname=? price=? where bid=?";
        return super.executeUpdate(sql, new String[] {"bname","price","bid"}, book);
    }
    
    
    /**
     * 新增
     * @param book
     * @return
     * @throws SQLException
     * @throws NoSuchFieldException
     * @throws SecurityException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public int add (Book book) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
        String sql="insert into t_mvc_book values(?,?,?)";
        return super.executeUpdate(sql, new String[] {"bid","bname","price"}, book);
    }
    
    /**
     * 删除
     * @param book
     * @return
     * @throws SQLException
     * @throws NoSuchFieldException
     * @throws SecurityException
     * @throws IllegalArgumentException
     * @throws IllegalAccessException
     */
    public int del (Book book) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
        String sql="delete from t_mvc_book where bid=?";
        return super.executeUpdate(sql, new String[] {"bid"}, book);
    }
}

BaseDao.java

package com.huang.util;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.huang.entity.Book;

public class BaseDao<T> {

    /**
     *         
     * @param sql        查询不同的实体类,那么对应的sql不同,所以需要传递
     * @param clz        生产出不同的实体类对应的实例,然后装进list容器中返回
     * @param pageBean        决定是否分页
     * @return
     * @throws SQLException
     * @throws InstantiationException
     * @throws IllegalAccessException
     */
    public List<T> executeQuery(String sql, Class clz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
        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(rs.getLong(1)+"");
            }
        
            //算出符合条件的结果集
            String pageSql=getPageSql(sql, pageBean);
            pst=con.prepareStatement(pageSql);
            rs=pst.executeQuery();
            
            
        }
        else {
            pst=con.prepareStatement(sql);
            rs=pst.executeQuery();
        }
        List<T> list=new ArrayList<>();
        T t;
        while(rs.next()) {
            /**
             * 1、实例化一个book对象(该对象为空)
             * 2、取book的所有属性,然后给其赋值
             *         2.1获取所有属性对象
             *         2.2给属性对象赋值
             * 3、赋完值的book对象装进list容器中
             */
            t=(T) clz.newInstance();
            Field[] fields=clz.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                field.set(t, rs.getObject(field.getName()));
            }
            list.add(t);
        }
        DBAccess.close(con, pst, rs);
        return list;
    }
    
    /**
     * 利用原生sql拼接出符合条件的结果集的查询sql
     * @param sql
     * @param pageBean
     * @return
     */
    private String getPageSql(String sql,PageBean pageBean) {
        return sql + " limit "+ pageBean.getStartIndex() +"," + pageBean.getRows();
    }
    
    /**
     * 获取符合条件的总记录数的sql语句
     * @param sql
     * @return
     */
    private String getCountSql(String sql) {
        return "select count(*) from ("+ sql +") t";
    }
    
    
    /**
     * 
     * @param sql    增删改
     * @param attrs    决定?位置
     * @param t    要操作的实体类
     * @return
     * @throws SQLException 
     * @throws SecurityException 
     * @throws NoSuchFieldException 
     * @throws IllegalAccessException 
     * @throws IllegalArgumentException 
     */
    public int executeUpdate(String sql,String[] attrs,T t) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
        Connection con=DBAccess.getConnection();
        PreparedStatement pst=con.prepareStatement(sql);
//        pst.setString(2, book.getBname());
//        pst.setFloat(3, book.getPrice());
//        pst.setInt(1, book.getBid());
        for (int i= 0; i <= attrs.length; i++) {
            Field f=t.getClass().getDeclaredField(attrs[i-1]);
            f.setAccessible(true);
            pst.setObject(i, f.get(t));
        }
        int num=pst.executeUpdate();
        DBAccess.close(con, pst, null);
        return num;
    }
    
}

2、增删改查的jsp页面

BookAction.java

package com.huang.web;

import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.huang.dao.BookDao;
import com.huang.entity.Book;
import com.huang.framework.ActionSupport;
import com.huang.framework.ModelDrivern;
import com.huang.util.PageBean;

public class BookAction extends ActionSupport implements ModelDrivern<Book> {

    private Book book=new Book();
    private BookDao bookDao=new BookDao();
    
    /**
     * 分页查询
     * @param req
     * @param resp
     * @return
     */
    public String list(HttpServletRequest req,HttpServletResponse resp) {
        PageBean pageBean=new PageBean();
        pageBean.setRequest(req);
        try {
            List<Book> list=this.bookDao.list(book, pageBean);
            req.setAttribute("bookList", list);
            req.setAttribute("pageBean", pageBean);
        } catch (InstantiationException | IllegalAccessException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "list";
    }
    
    /**
     * 跳转到增加或者修改页面
     * @param req
     * @param resp
     * @return
     * @throws InstantiationException
     * @throws IllegalAccessException
     * @throws SQLException
     */
    public String preSave(HttpServletRequest req,HttpServletResponse resp)  {
//        bid的类型是int类型,而int类型的默认值是0;如果jsp未传递bid的参数值,那么bid=0
        if(book.getBid()==0) {
            System.out.println("增加逻辑....");
        }
        else {
//            修改数据回显逻辑
            try {
                Book b=this.bookDao.list(book, null).get(0);
                req.setAttribute("book", b);
            } catch (InstantiationException | IllegalAccessException | SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return "edit";
    }
    
    /**
     * 新增
     * @param req
     * @param resp
     * @return
     */
    public String add(HttpServletRequest req,HttpServletResponse resp)  {
    try {
        this.bookDao.add(book);
    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
            | SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
        return "toList";
    }
    /**
     * 修改
     * @param req
     * @param resp
     * @return
     */
    public String edit(HttpServletRequest req,HttpServletResponse resp)  {
        try {
            this.bookDao.edit(book);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
                | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            return "toList";
        }
    
    public String del(HttpServletRequest req,HttpServletResponse resp)  {
        try {
            this.bookDao.del(book);
        } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException
                | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
            return "toList";
        }
    
    @Override
    public Book getModel() {
        return book;
    }

}

bookList.js

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="my" uri="/huang" %>
<!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"> <title>Insert title here</title> </head> <body> <h2>小说目录</h2> <br> <form action="${pageContext.request.contextPath}/book.action?methodName=list" method="post"> 书名:<input type="text" name="bname"> <input type="submit" value="确定"> </form> <a href="${pageContext.request.contextPath}/book.action?methodName=preSave">增加</a> <table border="1" width="100%"> <tr> <td>编号</td> <td>名称</td> <td>价格</td> <td>操作</td> </tr> <c:forEach items="${bookList }" var="b"> <tr> <td>${b.bid }</td> <td>${b.bname }</td> <td>${b.price }</td> <td> <a href="${pageContext.request.contextPath}/book.action?methodName=preSave&&bid=${b.bid}">修改</a>&nbsp;&nbsp;&nbsp; <a href="${pageContext.request.contextPath}/book.action?methodName=del&&bid=${b.bid}">删除</a>&nbsp;&nbsp;&nbsp; </td> </tr> </c:forEach> <z:page pageBean="${pageBean }"></z:page> </table> </body> </html>
原文地址:https://www.cnblogs.com/bf6rc9qu/p/11099845.html