在做增删改之前要先导入之前所学过的一些工具类以及jar包
需要导入的jar包
导入之前所写过的工具类等
将处理中文乱码的配置加入安全目录下的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>web_mvc</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 处理中文乱码 -->
<filter>
<filter-name>encodingFiter</filter-name>
<filter-class>com.xfz.util.EncodingFiter</filter-class>
</filter>
<filter-mapping>
<filter-name>encodingFiter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>com.xfz.framework.DispatcherServlet</servlet-class>
<init-param>
<param-name>mvcXmlLocation</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>
准备工作到这里结束,开始编码
写一个BookDao继承BaseDao
先写分页的查询,再写增删改的一些通用方法
注意:用完数据库连接的一些方法时要记得关闭数据库,否则在后面的课程中会出现太多连接的错误
package com.xfz.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import com.xfz.entity.Book;
import com.xfz.util.BaseDao;
import com.xfz.util.DBAccess;
import com.xfz.util.PageBean;
import com.xfz.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);
}
//增加
public int add(Book book) throws SQLException, IllegalArgumentException, IllegalAccessException {
String sql="insert into t_mvc_book values (?,?,?)";
return super.executeUpdate(sql, new String[] {"bid","bname","price"},book);
}
//修改
public int edit(Book book) throws SQLException, IllegalArgumentException, IllegalAccessException {
String sql="update t_mvc_book set bname=?,price=? where bid=?";
return super.executeUpdate(sql, new String[] {"bname","price","bid"},book);
}
//删除
public int del(Book book) throws SQLException, IllegalArgumentException, IllegalAccessException {
String sql="delete from t_mvc_book where bid=?";
return super.executeUpdate(sql, new String[] {"bid"},book);
}
public static void main(String[] args) {
BookDao bookDao=new BookDao();
Book book=new Book(141313, "啦啦啦", 56);
try {
bookDao.del(book);
} 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();
}
}
}
将BookDao中的重复的代码封装起来
在这里插入代码片package com.xfz.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.xfz.entity.Book;
/**
* @author ld
* @param <T>
* 用来处理所有表的通用的增删改查
*
* 查询指的是通用分页的查询
*/
public class BaseDao<T> {
/**
* @param sql 可能不同的表,那么意味着sql是变化的,那么它是从子类处理好再传到父类
* @param claz 需要返回不同的对象集合 Book.class/Order.class
* @param pagebean 可能要分页
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws InstantiationException
*/
public List<T> executeQuery(String sql,Class claz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
List<T> list=new ArrayList<>();
//建立连接
Connection con=DBAccess.getConnection();
//拿到处理对象
PreparedStatement ps=null;
ResultSet rs=null;
if(pageBean !=null && pageBean.isPagination()) {//是否分页
//分页
/**
* 分析:
* 1.分页与pagebean中total 意味着需要查询数据库得到total赋值给pagebean
* 2.查询出符合条件的某一页的数据
*/
//通过原生sql拼接出查询符合条件的总记录数的sql语句
//select count(*) from (select * from t_mvc_book where bname like '%圣墟%') t;
String countSql=getCountSql(sql);
ps=con.prepareStatement(countSql);
rs=ps.executeQuery();
if(rs.next()) {
pageBean.setTotal(rs.getObject(1).toString());
}
//select * from t_mvc_book where bname like '%圣墟%' limit 0,10;
String pageSql=getPageSql(sql,pageBean);
ps=con.prepareStatement(pageSql);
rs=ps.executeQuery();
}else {
//不分页
ps=con.prepareStatement(sql);
rs=ps.executeQuery();
}
T t=null;
while(rs.next()) {//如果说游标有下一个就放到list集合中
//list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
t=(T) claz.newInstance();//t 相当于book对象
//获取所有属性
Field [] fields=claz.getDeclaredFields();
//给每一个属性赋值
for (Field f : fields) {
//打开访问权限
f.setAccessible(true);
f.set(t, rs.getObject(f.getName()));
}
list.add(t);
}
DBAccess.close(con, ps, rs);
return list;
}
private String getPageSql(String sql,PageBean pageBean) {
// TODO Auto-generated method stub
return sql+" limit "+pageBean.getStartIndex()+","+pageBean.getRows();
}
private String getCountSql(String sql) {
// TODO Auto-generated method stub
return "select count(1) from ("+sql+") t";
}
/**
* @param sql 代表增删改的sql语句
* @param attrs 代表sql语句中的问号
* @param t 实体类(里面包含了参数值)
* @return
* @throws SQLException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
public int executeUpdate(String sql,String [] attrs,T t) throws IllegalArgumentException, IllegalAccessException, SQLException {
Connection con=DBAccess.getConnection();
PreparedStatement ps=con.prepareStatement(sql);
// ps.setInt(1, book.getBid());
// ps.setString(2, book.getBname());
// ps.setFloat(3, book.getPrice());
//反射
Field field=null;
//拿到所有的属性对象并且遍历
for (int i = 0; i < attrs.length; i++) {
try {
field=t.getClass().getDeclaredField(attrs[i]);
field.setAccessible(true);
ps.setObject(i+1,field.get(t));
} catch (NoSuchFieldException | SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
int num=ps.executeUpdate();
DBAccess.close(con, ps, null);
return num;
}
}
然后在BookDao中进行增删测试
打开数据库输入查询语句,然后运行代码之后再运行查询语句
增加结果:
删除结果:
接着写web层,写一个BookAction继承ActionSupport并且实现模拟驱动接口ModelDriven
写入五个方法增删改查注意还有新增修改的跳转页面的方法
package com.xfz.web;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.xfz.dao.BookDao;
import com.xfz.entity.Book;
import com.xfz.framework.ActionSupport;
import com.xfz.framework.ModelDriven;
import com.xfz.util.PageBean;
public class BookAction extends ActionSupport implements ModelDriven<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
* 跳转新增修改页面(新增修改页面是同一个)
*/
public String preSave(HttpServletRequest req,HttpServletResponse resp) {
if(book.getBid()!=0) {
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 (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 (IllegalArgumentException | IllegalAccessException | 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 | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "toList";
}
@Override
public Book getModel() {
return book;
}
}
配置conf里面的mvc.xml文件
注意:增删改的时候一定要用重定向不能用转发,查询则用转发,因为查询要携带参数到页面上去
<?xml version="1.0" encoding="UTF-8"?>
<!--
config标签:可以包含0~N个action标签
-->
<config>
<action path="/cal" type="com.xfz.web.CalAction">
<forward name="rs" path="/rs.jsp" redirect="false" />
</action>
<!-- 增删改的时候一定要用重定向不能用转发 -->
<action path="/book" type="com.xfz.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"/>
</action>
</config>
后台代码到这里结束,开始写前台代码
写一个书籍主页的jsp页面和一个书籍编辑的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="/xiefuzhen" prefix="fz"%>
<!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="hidden" name="rows" value="20"> -->
<!-- <input type="hidden" name="pagination" value="false"> -->
书名:<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>
<a href="${pageContext.request.contextPath}/book.action?methodName=del&&bid=${b.bid}">删除</a>
</td>
</tr>
</c:forEach>
</table>
<fz:page pageBean="${pageBean}"></fz:page>
</body>
</html>
书籍编辑:
<%@ 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></title>
</head>
<body>
<form action="${pageContext.request.contextPath}/book.action?methodName=${book.bname==null ? 'add' :'edit'}" method="post">
bid:<input type="text" value="${book.bid}" name="bid"><br>
bname:<input type="text" value="${book.bname}" name="bname"><br>
price:<input type="text" value="${book.price}" name="price"><br>
<input type="submit" value="ok">
</form>
</body>
</html>
如果要访问数据的话浏览地址必须要写成:自己的项目名/book.action?methodName=list不然会没有数据
增加界面显示:
数据库中:
修改界面显示:
删除界面显示(数据库):