自定义mvc增删改查

一、搭建自定义mvc框架环境


1、将上一次写的框架导出成为jar包——>选择JAR file——>在JAR file这可以输入你想导出的位置——>最后点击finish就可以了

2、将导出的jar包导入到现在所要使用的项目中并且将所有要用到的jar包导入——>将之前写的tag标签导入——>引入通用分页所写的代码

二、通用增删改查

1.通用类BaseDao


package com.dgl.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;
 
 
 
public class BaseDao<T> {
 
	public List<T> executeQuery( String sql,PageBean pagebean,CallBack<T> callBack) throws Exception{
		
		/**
		 * 1.拿到数据库连接
		 * 2.拿到preparstatement
		 * 3.执行sql语句
		 */
		
		Connection con = null;
		
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		if(pagebean!=null&&pagebean.isPagination()) {
			String countsql = getCountsql(sql);
			 con = DBAccess.getConnection();
			 ps = con.prepareStatement(countsql);
			 rs = ps.executeQuery();
			 if(rs.next()) {
				 pagebean.setTotal(rs.getString("n"));
	
			 }
			 String pageSql= getpageSql(sql,pagebean);
			 con = DBAccess.getConnection();
			 ps = con.prepareStatement(pageSql);
			 rs = ps.executeQuery();
		}else {
			 con = DBAccess.getConnection();
			 ps = con.prepareStatement(sql);
			 rs = ps.executeQuery();
		}
		//查询不同的表必然要处理不同的结果集
		return callBack.foreach(rs);
	}
 
	/**
	 * 拼接第N页数据的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) {
		// TODO Auto-generated method stub
		return " select count(1) as n from ("+sql+") t";
	}
	
	
	/**
	 * 通用增删改
	 * @param sql sql语句
	 * @param t 泛类
	 * @param strings 属性数组
	 * @return
	 * @throws Exception 抛异常
	 */
	
	public int executeUpdate(String sql,T t,String[] strings) throws Exception {
		Connection con = DBAccess.getConnection();
		PreparedStatement ps = con.prepareStatement(sql);
		//将t的某一个对应值加到ps对象中
		for (int i = 0; i < strings.length; i++) {
			Field f = t.getClass().getDeclaredField(strings[i] );
			f.setAccessible(true);
			f.get(t);
			ps.setObject(i+1, f.get(t));//下标从0开始
		}
		
		
		return ps.executeUpdate();
	}
}

2.BookDao 

根据方法的不同,sql语句和参数也不同

package com.dgl.dao;
 
import java.util.ArrayList;
import java.util.List;
 
import com.dgl.entity.Book;
import com.dgl.util.BaseDao;
import com.dgl.util.PageBean;
import com.dgl.util.StringUtils;
 
public class BookDao extends BaseDao<Book>{
 
	/**
	 * 查询
	 * @param book 实体类
	 * @param pagebean 分页
	 * @return
	 * @throws Exception 抛异常
	 */
	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+"%'";
		}
		int bid = book.getBid();
		if(bid !=0) {
			sql +=" and bid = "+bid;
			
		}
		
		//调用父类的查询方法
		return super.executeQuery(sql, pagebean, rs->{
			List<Book> list = new ArrayList<>();
			try {
				while(rs.next()) {
					list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return list;
		});
	}
	
	
	
	/**
	 * 增加方法
	 * @param book 实体类书籍
	 * @return 父类中的通用增删改方法
	 * @throws Exception
	 */
	public int add(Book book) throws Exception {
		String sql = "insert into t_mvc_book values(?,?,?)";
		return super.executeUpdate(sql, book, new String[] {"bid","bname","price"});
	}
	 
	/**
	 * 删除方法
	 * @param book 实体类书籍
	 * @return 父类中的通用增删改方法
	 * @throws Exception
	 */
	public int delete(Book book) throws Exception {
		String sql = "delete from t_mvc_book where bid = ?";
		return super.executeUpdate(sql, book, new String[] {"bid"});
	}
	
	 
		/**
		 * 修改方法
		 * @param book 实体类书籍
		 * @return 父类中的通用增删改方法
		 * @throws Exception
		 */
	public int edit(Book book) throws Exception {
		String sql = "update t_mvc_book set bname=?,price=? where bid=?";
		return super.executeUpdate(sql, book, new String[] {"bname","price","bid"});
	}

3、在BookAction中写好对应的方法

遵循先继承后实现的规则,分别调用父类和接口的方法

public class BookAction extends ActionSupport implements ModelDriven<Book>{
 
	private Book book = new Book();
	private BookDao bd = new BookDao();
	@Override
	public Book getModel() {
		// TODO Auto-generated method stub
		return null;
	}
 
	
 
	//增加
	public String add(HttpServletRequest req, HttpServletResponse resp) {
		try {
			bd.add(book);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "toList";
	}
	
	//删除
		public String delete(HttpServletRequest req, HttpServletResponse resp) {
			try {
				bd.delete(book);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "toList";
		}
		
		//修改
		//增加
		public String edit(HttpServletRequest req, HttpServletResponse resp) {
			try {
				bd.edit(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=bd.list(book, pageBean);
			req.setAttribute("books", list);
			req.setAttribute("pageBean", pageBean);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "list";
	}
	
	public String toEdit(HttpServletRequest req,HttpServletResponse resp)  {
		try {
			if(book.getBid()!=0) {
				List<Book> list=bd.list(book, null);
				req.setAttribute("b", list.get(0));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "toEdit";
 

4、在Junit中测试

package com.dgl.dao;
 
import static org.junit.jupiter.api.Assertions.*;
 
import java.util.List;
 
import org.junit.jupiter.api.Test;
 
import com.dgl.entity.Book;
 
class BookDaoTest {
 
	private BookDao bookDao=new BookDao();
 
	
 
	@Test
	public void testList() {
		try {
			List<Book> list = bookDao.list(new Book(), null);
			for (Book book : list) {
				System.out.println(book);
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
 
	//增加
	@Test
	public void testAdd() {
		Book book = new Book(123, "小朱", 9999);
		try {
			bookDao.add(book);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
 
	
 
	//修改
	@Test
	public void testEdit() {
		
			Book book = new Book(123, "小朱爸爸", 9999);
			try {
				bookDao.edit(book);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
 
	}
	
	//删除
 
	@Test
	public void testDelete() {
	
		Book book = new Book(123, "小朱爸爸", 9999);
		try {
			bookDao.delete(book);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
 
	

三、前端Jsp界面

1、主界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.zhujiayin.dgl" 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>
<style type="text/css">
.page-item input {
	padding: 0;
	width: 40px;
	height: 100%;
	text-align: center;
	margin: 0 6px;
}
 
.page-item input, .page-item b {
	line-height: 38px;
	float: left;
	font-weight: 400;
}
 
.page-item.go-input {
	margin: 0 10px;
}
</style>
</head>
<body>
	<form class="form-inline"
		action="${pageContext.request.contextPath }/book.action?methodName=list"
		method="post">
		<div class="form-group mb-2">
			<input type="text" class="form-control-plaintext" name="bname"
				placeholder="请输入书籍名称">
			<!-- 			<input name="rows" value="20" type="hidden"> -->
			<!-- 不想分页 -->
			<input name="pagination" value="false" type="hidden">
		</div>
		<button type="submit" class="btn btn-primary mb-2">查询</button>
		<a class="btn btn-primary mb-2"
			href="${pageContext.request.contextPath }/book.action?methodName=toEdit">新增</a>
	</form>
 
	<table class="table table-striped bg-success">
		<thead>
			<tr>
				<th scope="col">书籍ID</th>
				<th scope="col">书籍名</th>
				<th scope="col">价格</th>
				<th scope="col">操作</th>
			</tr>
		</thead>
		<tbody>
			<c:forEach var="b" items="${books }">
				<tr>
					<td>${b.bid }</td>
					<td>${b.bname }</td>
					<td>${b.price }</td>
					<td><a
						href="${pageContext.request.contextPath }/book.action?methodName=toEdit&bid=${b.bid}">修改</a>
						<a
						href="${pageContext.request.contextPath }/book.action?methodName=delete&bid=${b.bid}">删除</a>
					</td>
				</tr>
			</c:forEach>
		</tbody>
	</table>
	<!-- 这一行代码就相当于前面分页需求前端的几十行了 -->
	<z:page pageBean="${ pageBean}"></z:page>
 
</body>
</html>

2、BookEdit(增加和修改的界面)

目录

一、搭建自定义mvc框架环境

二、通用增删改查

1.通用类BaseDao

2.BookDao 

根据方法的不同,sql语句和参数也不同

3、在BookAction中写好对应的方法

遵循先继承后实现的规则,分别调用父类和接口的方法

4、在Junit中测试

三、前端Jsp界面

1、主界面

2、BookEdit(增加和修改的界面)


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值