mvc的增删改查

mvc的增删改查

  • 1.首先要建立连接
  • 2.建个连接到数据库实体类book
  • 3、第三步写dao方法
    • bookdao继承 BaseDao传一个Book
    • BaseDao.java 通用的增删改方法
    • 增删改查子控制器
  • 4.测试类
    • 写一个测试类BookDaoTest.java
  • 5、第五步 配置 mvc.xml和web.xml
  • 6、jsp增删改的功能页面展示

1.首先要建立连接

package com.zking.mvcplus.util;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
 * 提供了一组获得或关闭数据库对象的方法
 * 
 */
public class DBAccess {
 private static String url;
 private static String driver;
 private static String user;
 private static String password;
 static {// 静态块执行一次,加载 驱动一次
  try {
   InputStream is = DBAccess.class
     .getResourceAsStream("config.properties");
   Properties properties = new Properties();
   properties.load(is);
   driver = properties.getProperty("driver");
   url = properties.getProperty("url");
   user = properties.getProperty("user");
   password = properties.getProperty("pwd");
   Class.forName(driver);
  } catch (Exception e) {
   e.printStackTrace();
   throw new RuntimeException(e);
  }
 }
 /**
  * 获得数据连接对象
  * 
  * @return
  */
 public static Connection getConnection() {
  try {
   Connection conn = DriverManager.getConnection(url, user, password);
   return conn;
  } catch (SQLException e) {
   e.printStackTrace();
   throw new RuntimeException(e);
  }
 }
 public static void close(ResultSet rs) {
  if (null != rs) {
   try {
    rs.close();
   } catch (SQLException e) {
    e.printStackTrace();
    throw new RuntimeException(e);
   }
  }
 }
 public static void close(Statement stmt) {
  if (null != stmt) {
   try {
    stmt.close();
   } catch (SQLException e) {
    e.printStackTrace();
    throw new RuntimeException(e);
   }
  }
 }
 public static void close(Connection conn) {
  if (null != conn) {
   try {
    conn.close();
   } catch (SQLException e) {
    e.printStackTrace();
    throw new RuntimeException(e);
   }
  }
 }
 public static void close(Connection conn, Statement stmt, ResultSet rs) {
  close(rs);
  close(stmt);
  close(conn);
 }
 public static boolean isOracle() {
  return "oracle.jdbc.driver.OracleDriver".equals(driver);
 }
 public static boolean isSQLServer() {
  return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver);
 }
 public static boolean isMysql() {
  return "com.mysql.jdbc.Driver".equals(driver);
 }
 public static void main(String[] args) {
  Connection conn = DBAccess.getConnection();
  DBAccess.close(conn);
  System.out.println("isOracle:" + isOracle());
  System.out.println("isSQLServer:" + isSQLServer());
  System.out.println("isMysql:" + isMysql());
  System.out.println("数据库连接(关闭)成功");
 }
}

2.建个连接到数据库实体类book


package com.zking.mvcplus.entity;
public class Book {
 private int bid;
 private String bname;
 private float price;
 @Override
 public String toString() {
  return "Book [bid=" + bid + ", bname=" + bname + ", price=" + 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;
 }
 public Book(int bid, String bname, float price) {
  super();
  this.bid = bid;
  this.bname = bname;
  this.price = price;
 }
 public Book() {
  super();
 }
}

3、第三步写dao方法

bookdao继承 BaseDao传一个Book

package com.zking.mvcplus.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import com.zking.mvcplus.entity.Book;
import com.zking.mvcplus.util.BaseDao;
import com.zking.mvcplus.util.DBAccess;
import com.zking.mvcplus.util.PageBean;
import com.zking.mvcplus.util.StringUtils;
public class BookDao extends BaseDao<Book>{
 public List<Book> ls(Book bk,PageBean pb) throws InstantiationException, IllegalAccessException, SQLException{
  String sql = "select * from t_mvc_book where true";
  if(StringUtils.isNotBlank(bk.getBname())) {
   sql +=" and banme like '%"+bk.getBname()+"%'";
  }
  return super.executeQuery(sql, Book.class, pb);
 }
 /**
  *  增加
  * @param bk 对book类进行操作
  * @return
  * @throws SQLException
  * @throws NoSuchFieldException
  * @throws SecurityException
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  */
 public int add(Book bk) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
  String sql ="insert into t_mvc_book values(?,?,?)";
  return super.executeUpdate(bk, sql, new String[] {"bid","bname","price"});
 }
 /**
  *   删除
  * @param bk
  * @return
  * @throws SQLException
  * @throws NoSuchFieldException
  * @throws SecurityException
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  */
 public int del(Book bk) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
  String sql ="delete from t_mvc_book where bid=?";
  return super.executeUpdate(bk, sql, new String[] {"bid"});
 }
 /**
  *  修改 
  * @param bk
  * @return
  * @throws SQLException
  * @throws NoSuchFieldException
  * @throws SecurityException
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  */
 public int update(Book bk) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
  String sql ="update t_mvc_book set bname=?,price=? where bid=?";
  return super.executeUpdate(bk, sql, new String[] {"bname","price","bid"});
 }
}

BaseDao.java 通用的增删改方法

package com.zking.mvcplus.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.zking.mvcplus.entity.Book;
/**
 * T = Book.class
 * T = Student.class
 * 
 * @author MRCHENIKE
 *
 * @param 
 */
public class BaseDao<T> {
 /**
  * 
  * @param sql  决定查询那张表的数据
  * @param clz  查询出来的数据封装到那个实体类中
  * @param paggBean 决定是否分页
  * @return
  * @throws IllegalAccessException 
  * @throws InstantiationException 
  * @throws SQLException 
  */
 public List<T> executeQuery(String sql, Class clz, PageBean paggBean) throws InstantiationException, IllegalAccessException, SQLException {
  List<T> ls = new ArrayList<>();
  Connection con = DBAccess.getConnection();
  PreparedStatement ps = null;
  ResultSet rs =null;
  try {
  if(paggBean!=null&& paggBean.isPagination()) {
   //分页
   String countSql = getCountSql(sql);
   ps = con.prepareStatement(countSql);
   rs = ps.executeQuery();
   if(rs.next()) {
    paggBean.setTotal(rs.getLong(1)+"");
   }
   String pageSql = getPageSql(sql,paggBean);
   ps = con.prepareStatement(pageSql);
   rs = ps.executeQuery();
  }
  else {
   ps = con.prepareStatement(sql);
   rs = ps.executeQuery();
  }
   while (rs.next()) {
    /**
     * 1.创建了一个Book对象
     * 2.从ResultSet结果集中获取值放入Book对象中属性中
       2.1 获 取到book的属性对象
       2.2给属性对象赋值
     * 3.将已经有值得book对象放入list集合中
     */
    T t = (T) clz.newInstance();
    Field[] fields = clz.getDeclaredFields();
    for (Field field : fields) {
     //给权限
     field.setAccessible(true);
     field.set(t, rs.getObject(field.getName()));
    }
    ls.add(t);
   } 
  } finally {
   DBAccess.close(con,ps,rs);
  }
  return ls;
 }
 /**
  *  通用的增删改方法
  * @param t 增删改的那个类的名字 
  * @param sql 增删改的sql语句
  * @param attrs ?所代表的实体类的属性
  * @return
  * @throws SQLException
  * @throws NoSuchFieldException
  * @throws SecurityException
  * @throws IllegalArgumentException
  * @throws IllegalAccessException
  */
 public int executeUpdate(T t,String sql,String[] attrs) throws SQLException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
  Connection con = DBAccess.getConnection();
  PreparedStatement ps = con.prepareStatement(sql);
  for (int i = 0; i < attrs.length; i++) {
   Field field = t.getClass().getDeclaredField(attrs[i]);
   field.setAccessible(true);
   ps.setObject(i+1, field.get(t));
  }
  return ps.executeUpdate();
 }
 /**
  * 将原生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(1) from (" + sql + ") t";
 }
}

增删改查子控制器

package com.zking.mvcplus.web;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lx.framework.ActionSupport;
import com.lx.framework.ModelDriven;
import com.zking.mvcplus.dao.BookDao;
import com.zking.mvcplus.entity.Book;
import com.zking.mvcplus.util.PageBean;
/**
 * 增删改查子控制器
 * @author MRCHENIKE
 *
 */
public class BookAction extends ActionSupport implements ModelDriven<Book>{
 private BookDao bd = new BookDao();
 private Book bk = new Book();
 /**
  *   查询数据分页的展示
  * @param req
  * @param resp
  * @return
  */
 public String ls(HttpServletRequest req,HttpServletResponse resp) {
  try {
   PageBean pb = new PageBean();
   pb.setRequest(req);
   List<Book> ls = this.bd.ls(bk, pb);
   req.setAttribute("bookList", ls);
   req.setAttribute("pageBean", pb);
   System.out.println(ls.size());
  } catch (InstantiationException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return "list";
 }
 
 /**
  *  增加书籍
  * @param req
  * @param resp
  * @return
  */
 public String add(HttpServletRequest req,HttpServletResponse resp) {
  try {
   this.bd.add(bk);
  } catch (NoSuchFieldException e) {
   e.printStackTrace();
  } catch (SecurityException e) {
   e.printStackTrace();
  } catch (IllegalArgumentException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return "toList";
 }
 
 /**
  * 删除书籍
  * @param req
  * @param resp
  * @return
  */
 public String del(HttpServletRequest req,HttpServletResponse resp) {
  bk.setBid(25000);
  try {
   this.bd.del(bk);
  } catch (NoSuchFieldException e) {
   e.printStackTrace();
  } catch (SecurityException e) {
   e.printStackTrace();
  } catch (IllegalArgumentException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return "toList";
 }
 /**
  *  加载需要修改的数据
  * @param req
  * @param resp
  * @return
  */
 public String load(HttpServletRequest req,HttpServletResponse resp) {
  try {
   List<Book> ls = this.bd.ls(bk, null);
   req.setAttribute("book", ls.get(0));
  } catch (InstantiationException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return "toEdit";
 }
 /**
  *  开始修改书籍信息
  * @param req
  * @param resp
  * @return
  */
 public String update(HttpServletRequest req,HttpServletResponse resp) {
  try {
   int reCode = this.bd.update(bk);
  } catch (NoSuchFieldException e) {
   e.printStackTrace();
  } catch (SecurityException e) {
   e.printStackTrace();
  } catch (IllegalArgumentException e) {
   e.printStackTrace();
  } catch (IllegalAccessException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return "toList";
 }
 @Override
 public Book getModel() {
  // TODO Auto-generated method stub
  return bk;
 }
}

4.测试类

写一个测试类BookDaoTest.java

package com.zrh.dao;
import java.sql.SQLException;
import java.util.List;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.zrh.entity.Book;
class BookDaoTest {
   private BookDao bookDao = new BookDao();
   private Book book = null;
   @BeforeEach
   void setUp() throws Exception {
   	book = new Book();
   }

   @AfterEach
   void tearDown() throws Exception {
   }

   @Test
   void testList() {
   	try {
   		List<Book> list = this.bookDao.list(book, null);
   		System.out.println(list.size());
   	} catch (InstantiationException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	} catch (IllegalAccessException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	} catch (SQLException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	}
   }

   @Test
   void testAdd() {
   	book.setBid(151);
   	book.setBname("斗破");
   	book.setPrice(10);
   	try {
   		this.bookDao.add(book);
   	} catch (NoSuchFieldException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	} catch (SecurityException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	} catch (IllegalArgumentException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	} catch (IllegalAccessException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	} catch (SQLException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	}
   }

   @Test
   void testDelete() {
   	book.setBid(151);
   	try {
   		this.bookDao.delete(book);
   	} catch (NoSuchFieldException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	} catch (SecurityException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	} catch (IllegalArgumentException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	} catch (IllegalAccessException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	} catch (SQLException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	}
   }

   @Test
   void testUpdate() {
   	book.setBid(151);
   	book.setBname("遮天");
   	book.setPrice(102);
   	try {
   		this.bookDao.update(book);
   	} catch (NoSuchFieldException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	} catch (SecurityException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	} catch (IllegalArgumentException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	} catch (IllegalAccessException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	} catch (SQLException e) {
   		// TODO Auto-generated catch block
   		e.printStackTrace();
   	}
   }

}

5、第五步 配置 mvc.xml和web.xml

  • mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE config[
<!ELEMENT config (action*)>
<!ELEMENT action (forward*)>
<!ELEMENT forward EMPTY>
<!ATTLIST action 
 path CDATA #REQUIRED
 type CDATA #REQUIRED
>
<!ATTLIST forward
 name CDATA #REQUIRED
 path CDATA #REQUIRED
 redirect (true|false) "false"
>
]>
<!--
 config标签:可以包含0~N个action标签
-->
<config>
<action path="/regAction" type="test.RegAction">
  <!-- forward标签:没有子标签; 
  name:字符串,同一action标签下的forward标签name值不能相同 ;
  path:/开头的字符串
  redirect:只能是false|true,允许空,默认值为false -->
 <forward name="failed" path="/reg.jsp" redirect="false" />
 <forward name="success" path="/login.jsp" redirect="true" />
</action>
<action path="/loginAction" type="test.LoginAction">
 <forward name="failed" path="/login.jsp" redirect="false" />
 <forward name="success" path="/main.jsp" redirect="true" />
</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>mvc_crud</display-name>
 <!--过滤编码格式  -->
 <filter>
  <filter-name>encodingFiter</filter-name>
  <filter-class>com.wt.util.EncodingFiter</filter-class>
 </filter>
 <filter-mapping>
  <filter-name>encodingFiter</filter-name>
  <url-pattern>/*
 
 
  actionServlet
  com.zking.framework.ActionServlet
 
 
  actionServlet
  *.action
 

6、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="/zking" 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">
<script type="text/javascript">
 function add(){
  window.location.href="bookEdit.jsp";
 }
 function update(bid){
  window.location.href="${pageContext.request.contextPath}/bookAction.action?methodName=load&&bid="+bid;
 }
 function del(bid){
  window.location.href="${pageContext.request.contextPath}/bookAction.action?methodName=del&&bid="+bid;
 }
</script>
<title>Insert title here</title>
</head>
<body>
 <h2>小说目录</h2>
 <%=System.currentTimeMillis() %>
 <br>
 <form action="${pageContext.request.contextPath}/bookAction.action?methodName=ls"
  method="post">
  书名:<input type="text" name="bname"> <input type="submit"
   value="确定">
 </form>
 <button onclick="add();">新增</button>
 <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>
     <button onclick="update(${b.bid });">修改</button>&nbsp;&nbsp;&nbsp;
     <button onclick="del(${b.bid });">删除</button>
    </td>
   </tr>
  </c:forEach>
 </table>
 <z:page pageBean="${pageBean }"></z:page>
</body>
</html>

你可能感兴趣的:(MVC)