mvc的增删改查
- 1.首先要建立连接
- 2.建个连接到数据库实体类book
- 3、第三步写dao方法
- bookdao继承 BaseDao传一个Book
- BaseDao.java 通用的增删改方法
- 增删改查子控制器
- 4.测试类
- 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);
}
}
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);
}
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"});
}
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"});
}
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;
public class BaseDao<T> {
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()) {
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;
}
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();
}
private String getPageSql(String sql,PageBean pageBean) {
return sql+ " limit "+pageBean.getStartIndex()+","+pageBean.getRows()+"";
}
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;
public class BookAction extends ActionSupport implements ModelDriven<Book>{
private BookDao bd = new BookDao();
private Book bk = new Book();
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";
}
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";
}
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";
}
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";
}
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() {
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) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Test
void testAdd() {
book.setBid(151);
book.setBname("斗破");
book.setPrice(10);
try {
this.bookDao.add(book);
} 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();
}
}
@Test
void testDelete() {
book.setBid(151);
try {
this.bookDao.delete(book);
} 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();
}
}
@Test
void testUpdate() {
book.setBid(151);
book.setBname("遮天");
book.setPrice(102);
try {
this.bookDao.update(book);
} 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();
}
}
}
5、第五步 配置 mvc.xml和web.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>
<?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>
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>
<button onclick="del(${b.bid });">删除</button>
</td>
</tr>
</c:forEach>
</table>
<z:page pageBean="${pageBean }"></z:page>
</body>
</html>