MVC(增删改查)

对t_mvc_book 表进行增删改查

1、把之前写的页面和jar包导入
在这里插入图片描述
2、dao层 通用的增删改方法
BaseDao

package com.zhoutubing.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;


/**
 * T代表你要对哪个实体类表进行分页查询
 * sql 查询不同的实体类,那么对应的sql不同,所以需要传递
 * clz 生长出不同的实体类对应的案例,然后装进list容器中返回
 * pageBean 决定是否分页
 * @author VULCAN
 *
 * @param <T>
 */
public class BaseDao<T>{
	public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
		Connection con = DBAccess.getConnection();
		PreparedStatement ps=null;
		ResultSet rs =null;
		if(pageBean!=null && pageBean.isPagination()) {
//			需要分页
//			算符合条件的总记录数
			String countsql=getCountsql(sql);
			ps=con.prepareStatement(countsql);
			rs = ps.executeQuery();
			while(rs.next()) {
				pageBean.setTotal(rs.getLong(1)+"");
			}
//			查询出符合条件的结果集
			String pageSql=getpageSql(sql,pageBean);
			ps=con.prepareStatement(pageSql);
			rs = ps.executeQuery();
			
		}else {
			ps=con.prepareStatement(sql);
			rs = ps.executeQuery();
		}
		List<T> list=new ArrayList<>();
		T  t;
		while(rs.next()) {
			/**
			 * 1.实例化一个Book对象
			 * 2.取Book的所有属性,然后给其赋值
			 * 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, ps, rs);
		return list;
		
	}
	/**
	 * 利用原生态的sql拼接出符合条件的结果集的查询sql
	 * @param sql
	 * @param pageBean
	 * @return
	 */
	private String getpageSql(String sql, PageBean pageBean) {
		// TODO Auto-generated method stub
		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) from ("+sql+") t";
	}
	
	/**
	 * 通用的增删改方法
	 * @param sql    决定增删改的一种
	 * @param attrs   决定?的位置 new String[]{"bid","bname","price"}
	 * @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 = 1; 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;
	}
}


BookDao

package com.zhoutubing.dao;

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

import com.zhoutubing.entity.Book;
import com.zhoutubing.util.BaseDao;
import com.zhoutubing.util.DBAccess;
import com.zhoutubing.util.PageBean;
import com.zhoutubing.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.isBlank(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 t_mvc_book where bid=?";
		return super.executeUpdate(sql, new String[] {"bid"}, book);
	}
}

3、web层(BookAction)

package com.zhoutubing.web;


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

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

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

public class BookAction extends ActionSupport implements ModelDrivern<Book>{
	//实现ModelDriven<Book> 前台传来的值,自动封装到book里面
	
	
	//定义一个   对Book增删改查
	private Book book=new Book();
	
	private BookDao bookDao=new BookDao(); 
	
	/**
	 * 前台访问分页的查询
	 */
	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
	 */
	
	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);//如果后面没写get(0)就是一个集合,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 (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException
				| 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 (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException
				| SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	
		return "toList";
	
	
	}
	/**
	 * 删除方法
	 * @param req
	 * @param resp
	 * @return
	 */
	
public String del(HttpServletRequest req,HttpServletResponse resp) {
		
		try {
			this.bookDao.del(book);
		} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException
				| SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "toList";
	
	
	}
	
	@Override
	public Book getModel() {
		// TODO Auto-generated method stub
		return book;
	}
	
	
	
	
}


xml配置(增删改一定要用重定向 )为了阻止多次上传请求带来数据重复的影响:

<?xml version="1.0" encoding="UTF-8"?>

<config>
	
	  <action path="/book" type="com.zhoutubing.web.BookAction">
		<forward name="list" path="/bookList.jsp" redirect="false" />
		<forward name="edit" path="/bookEdit.jsp" redirect="false" />
	   <!--     增删改一定要用重定向 -->
		<forward name="toList" path="/book.action?methodName=list"></forward>
		
	</action>
</config>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>web05_mvc</display-name>
  
    <filter>
  	<filter-name>encodingFiter</filter-name>
  	<filter-class>com.zhoutubing.util.EncodingFiter</filter-class>
  </filter>
  <filter-mapping>
  	<filter-name>encodingFiter</filter-name>
  	<url-pattern>*.action</url-pattern>
  </filter-mapping>

 <servlet>
  <servlet-name>dispatcherServlet</servlet-name>
  <servlet-class>com.zhoutubing.framework.DispatcherServlet</servlet-class>
  <init-param>
     <param-name>xmlPath</param-name>
     <param-value>/mvc.xml</param-value>
  </init-param>
 </servlet>
 <servlet-mapping>
  <servlet-name>dispatcherServlet</servlet-name>
  <url-pattern>*.action</url-pattern>
 </servlet-mapping>
</web-app>

4、jsp 页面

bookList.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    <%@ taglib uri="/zhoutubing" prefix="z" %>
<!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="确定">
			<input type="hidden" name="pagination" value=true>
			<input type="hidden" name="rows" value="20">
	</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;
				      <a href="${pageContext.request.contextPath}/book.action?methodName=del&&bid=${b.bid}">删除</a>&nbsp;
				</td>
			</tr>
		</c:forEach>
	</table>
	<z:page pageBean="${pagebean }"></z:page>
</body>
</html>

bookEdit.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>
<form action="${pageContext.request.contextPath}/book.action" method="post">
    <input type="hidden" name="methodName" value="${b.bname == null ? 'add' : 'edit'}">
    书籍ID:<input type="text" name="bid" value="${book.bid }"><br>
    书籍名称:<input type="text" name="bname" value="${book.bname }"><br>
    书籍价格:<input type="text" name="price" value="${book.price }"><br>
    <input type="submit">
</form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值