老规矩思维导图
?
?上图,之前的增删查改
上图,现在的增删查改?
优化后自定义mvc效果图,代码如下
?BookDao类
package com.lj.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import com.zking.entity.Book;
import com.zking.util.BaseDao;
import com.zking.util.DBAccess;
import com.zking.util.PageBean;
import com.zking.util.StringUtils;
public class BookDao extends BaseDao<Book>{
/**
* 现状:增删改
* 1.写sql
* 2.建立链接
* 3.预定义对象PreparedStatement
* 4.设置参数
* 5.执行sql
* 解决:
*
* @param book
* @throws Exception
*/
// public void add(Book book) throws Exception {
// String sql = "insert into t_mvc_book values(?,?,?)";
// Connection con = DBAccess.getConnection();
// PreparedStatement pst = con.prepareStatement(sql);
// pst.setObject(1, book.getBid());
// pst.setObject(2, book.getBname());
// pst.setObject(3, book.getPrice());
// pst.executeUpdate();
// }
public void add(Book book) throws Exception {
String sql = "insert into t_mvc_book values(?,?,?)";
super.executeUpdate(sql, book, new String[] {"bid","bname","price"});
}
public void delete(Book book) throws Exception {
String sql = "delete from t_mvc_book where bid = ?";
super.executeUpdate(sql, book, new String[] {"bid"});
}
public void edit(Book book) throws Exception {
String sql = "update t_mvc_book set bname = ?,price = ? where bid = ?";
super.executeUpdate(sql, book, new String[] {"bname","price","bid"});
}
public List<Book> list(Book book,PageBean pageBean) throws Exception {
String sql = "select * from t_mvc_book where 1=1 ";
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 static void main(String[] args) throws Exception {
Book book = new Book();
book.setBid(23224);
// book.setBname("23225");
// book.setPrice(23225f);
BookDao bookDao = new BookDao();
// bookDao.add(book);
// bookDao.edit(book);
bookDao.delete(book);
}
}
Book类
package com.lj.entity;
public class Book {
private int bid;
private String bname;
private float 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;
}
@Override
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
}
}
PageTag类
package com.lj.tag;
import java.io.IOException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyTagSupport;
import com.zking.util.PageBean;
public class PageTag extends BodyTagSupport{
private PageBean pageBean;// 包含了所有分页相关的元素
public PageBean getPageBean() {
return pageBean;
}
public void setPageBean(PageBean pageBean) {
this.pageBean = pageBean;
}
@Override
public int doStartTag() throws JspException {
// 没有标签体,要输出内容
JspWriter out = pageContext.getOut();
try {
out.print(toHTML());
} catch (IOException e) {
e.printStackTrace();
}
return super.doStartTag();
}
private String toHTML() {
StringBuffer sb = new StringBuffer();
// 隐藏的form表单---这个就是上一次请求下次重新发的奥义所在
// 上一次请求的URL
sb.append("<form action='"+pageBean.getUrl()+"' id='pageBeanForm' method='post'>");
sb.append(" <input type='hidden' name='page'>");
// 上一次请求的参数
Map<String, String[]> paramMap = pageBean.getParamMap();
if(paramMap != null && paramMap.size() > 0) {
Set<Entry<String, String[]>> entrySet = paramMap.entrySet();
for (Entry<String, String[]> entry : entrySet) {
// 参数名
String key = entry.getKey();
// 参数值
for (String value : entry.getValue()) {
// 上一次请求的参数,再一次组装成了新的Form表单
// 注意:page参数每次都会提交,我们需要避免
if(!"page".equals(key)) {
sb.append(" <input type='hidden' name='"+key+"' value='"+value+"' >");
}
}
}
}
sb.append("</form>");
// 分页条
sb.append("<ul class='pagination justify-content-center'>");
sb.append(" <li class='page-item "+(pageBean.getPage() == 1 ? "disabled" : "")+"'><a class='page-link'");
sb.append(" href='javascript:gotoPage(1)'>首页</a></li>");
sb.append(" <li class='page-item "+(pageBean.getPage() == 1 ? "disabled" : "")+"'><a class='page-link'");
sb.append(" href='javascript:gotoPage("+pageBean.previousPage()+")'><</a></li>");// less than 小于号
// sb.append(" <li class='page-item'><a class='page-link' href='#'>1</a></li>");
// sb.append(" <li class='page-item'><a class='page-link' href='#'>2</a></li>");
sb.append(" <li class='page-item active'><a class='page-link' href='#'>"+pageBean.getPage()+"</a></li>");
sb.append(" <li class='page-item "+(pageBean.getPage() == pageBean.maxPage() ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.nextPage()+")'>></a></li>");
sb.append(" <li class='page-item "+(pageBean.getPage() == pageBean.maxPage() ? "disabled" : "")+"'><a class='page-link' href='javascript:gotoPage("+pageBean.maxPage()+")'>尾页</a></li>");
sb.append(" <li class='page-item go-input'><b>到第</b><input class='page-link'");
sb.append(" type='text' id='skipPage' name='' /><b>页</b></li>");
sb.append(" <li class='page-item go'><a class='page-link'");
sb.append(" href='javascript:skipPage()'>确定</a></li>");
sb.append(" <li class='page-item'><b>共"+pageBean.getTotal()+"条</b></li>");
sb.append("</ul>");
// 分页执行的JS代码
sb.append("<script type='text/javascript'>");
sb.append(" function gotoPage(page) {");
sb.append(" document.getElementById('pageBeanForm').page.value = page;");
sb.append(" document.getElementById('pageBeanForm').submit();");
sb.append(" }");
sb.append(" function skipPage() {");
sb.append(" var page = document.getElementById('skipPage').value;");
sb.append(" if (!page || isNaN(page) || parseInt(page) < 1 || parseInt(page) > "+pageBean.maxPage()+") {");
sb.append(" alert('请输入1~"+pageBean.maxPage()+"的数字');");
sb.append(" return;");
sb.append(" }");
sb.append(" gotoPage(page);");
sb.append(" }");
sb.append("</script>");
return sb.toString();
}
}
BaseDao类
package com.lj.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.entity.Book;
import com.zking.util.DBAccess;
import com.zking.util.PageBean;
import com.zking.util.StringUtils;
/**
* 所有Dao层的父类
* BookDao
* UserDao
* OrderDao
* ...
* @author Administrator
*
* @param <T>
*/
public class BaseDao<T> {
/**
* 通用的增删改
* @param sql 具体的增删改SQL
* @param t 具体要操作的表对应实体类
* @param attrs 具体操作表的某些字段对应的实体类属性
* @throws SQLException
*/
public void executeUpdate(String sql, T t, String[] attrs) throws Exception {
// attrs = new String[] {"bid","bname","price"};
// ?->bid;?->bname;?->price
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
// pst.setObject(1, book.getBid());
// pst.setObject(2, book.getBname());
// pst.setObject(3, book.getPrice());
for (int i = 0; i < attrs.length; i++) {
// attrs[0]=bid;
Field f = t.getClass().getDeclaredField(attrs[i]);
f.setAccessible(true);
// f.get(t); bid.get(book)
pst.setObject(i+1, f.get(t));
}
pst.executeUpdate();
}
/**
* 通用分页查询
* @param sql
* @param clz
* @return
* @throws Exception
*/
public List<T> executeQuery(String sql,Class<T> clz,PageBean pageBean) throws Exception{
List<T> list = new ArrayList<T>();
Connection con = DBAccess.getConnection();;
PreparedStatement pst = null;
ResultSet rs = null;
/*
* 是否需要分页?
* 无需分页(项目中的下拉框,查询条件教员下拉框,无须分页)
* 必须分页(项目中列表类需求、订单列表、商品列表、学生列表...)
*/
if(pageBean != null && pageBean.isPagination()) {
// 必须分页(列表需求)
String countSQL = getCountSQL(sql);
pst = con.prepareStatement(countSQL);
rs = pst.executeQuery();
if(rs.next()) {
pageBean.setTotal(String.valueOf(rs.getObject(1)));
}
// 挪动到下面,是因为最后才处理返回的结果集
// -- sql=SELECT * FROM t_mvc_book WHERE bname like '%圣墟%'
// -- pageSql=sql limit (page-1)*rows,rows 对应某一页的数据
// -- countSql=select count(1) from (sql) t 符合条件的总记录数
String pageSQL = getPageSQL(sql,pageBean);//符合条件的某一页数据
pst = con.prepareStatement(pageSQL);
rs = pst.executeQuery();
}else {
// 不分页(select需求)
pst = con.prepareStatement(sql);//符合条件的所有数据
rs = pst.executeQuery();
}
while (rs.next()) {
T t = clz.newInstance();
Field[] fields = clz.getDeclaredFields();
for (Field f : fields) {
f.setAccessible(true);
f.set(t, rs.getObject(f.getName()));
}
list.add(t);
}
return list;
}
/**
* 将原生SQL转换成符合条件的总记录数countSQL
* @param sql
* @return
*/
private String getCountSQL(String sql) {
// -- countSql=select count(1) from (sql) t 符合条件的总记录数
return "select count(1) from ("+sql+") t";
}
/**
* 将原生SQL转换成pageSQL
* @param sql
* @param pageBean
* @return
*/
private String getPageSQL(String sql,PageBean pageBean) {
// (this.page - 1) * this.rows
// pageSql=sql limit (page-1)*rows,rows
return sql + " limit "+ pageBean.getStartIndex() +","+pageBean.getRows();
}
}
BookAction类
package com.lj.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zking.dao.BookDao;
import com.zking.entity.Book;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.PageBean;
public class BookAction extends ActionSupport implements ModelDriver<Book>{
private Book book = new Book();
private BookDao bookDao = new BookDao();
@Override
public Book getModel() {
return book;
}
public String add(HttpServletRequest req, HttpServletResponse resp) {
try {
bookDao.add(book);
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
public String delete(HttpServletRequest req, HttpServletResponse resp) {
try {
bookDao.delete(book);
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
public String edit(HttpServletRequest req, HttpServletResponse resp) {
try {
bookDao.edit(book);
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
public String list(HttpServletRequest req, HttpServletResponse resp) {
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
try {
List<Book> list = bookDao.list(book, pageBean);
req.setAttribute("books", list);
req.setAttribute("pageBean", pageBean);
} catch (Exception e) {
e.printStackTrace();
}
return "list";
}
public String toEdit(HttpServletRequest req, HttpServletResponse resp) {
// 濡傛灉璺宠浆鐨勬槸鏂板鐣岄潰鏃犻渶鏌ヨ锛屽鏋滆烦杞殑鏄慨鏀圭晫闈紝闇�瑕佹煡璇㈠綋鍓峛id瀵瑰簲鐨勬暟鎹紝鍥炴樉鍒扮晫闈�
if(book.getBid() != 0) {
try {
// bid=16
List<Book> list = bookDao.list(book, null);
req.setAttribute("b", list.get(0));
} catch (Exception e) {
e.printStackTrace();
}
}
return "toEdit";
}
}
|