mvc实现增删改查
BaseDao(通用方法类)
package com.zhouzhuolin.mvc.dao;
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.zhouzhuolin.mvc.util.DBAccess;
import com.zhouzhuolin.mvc.util.PageBean;
public class BaseDao<T> {
public List<T> queryBookList(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();
if (rs.next()) {
pageBean.setTotal(rs.getLong(1)+"");
}
System.out.println("总记录数:"+pageBean.getTotal());
String PagerSql=getPagerSql(sql, pageBean);
ps=con.prepareStatement(PagerSql);
rs=ps.executeQuery();
}else {
ps=con.prepareStatement(sql);
rs=ps.executeQuery();
}
List<T> list=new ArrayList<T>();
T t;
while (rs.next()) {
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;
}
public String getCountSql(String sql) {
return "select count(*) from ("+sql+") t";
}
public String getPagerSql(String sql,PageBean pageBean) {
return sql+" limit "+pageBean.getStartIndex()+","+pageBean.getRows();
}
public int executeUpdate(String sql,T t,String[] str) throws SQLException, InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException {
Connection con=DBAccess.getConnection();
PreparedStatement ps=con.prepareStatement(sql);
for (int i = 1; i <=str.length; i++) {
Field f = t.getClass().getDeclaredField(str[i-1]);
f.setAccessible(true);
ps.setObject(i, f.get(t));
}
int n=ps.executeUpdate();
DBAccess.close(con, ps, null);
return n;
}
}
BookDao(方法层)
package com.zhouzhuolin.mvc.dao;
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.zhouzhuolin.mvc.entity.Book;
import com.zhouzhuolin.mvc.util.DBAccess;
import com.zhouzhuolin.mvc.util.PageBean;
import com.zhouzhuolin.mvc.util.StringUtils;
public class BookDao extends BaseDao<Book>{
private Connection con=null;
private PreparedStatement ps=null;
private ResultSet rs=null;
public int addBook(Book book) throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, SQLException {
String sql="insert into book(bookname,price,booktype) values(?,?,?)";
return super.executeUpdate(sql, book,new String[] {"bookname","price","booktype"});
}
public int editBook(Book book) throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, SQLException {
String sql="update book set bookname=?,price=?,booktype=? where id=?";
return super.executeUpdate(sql, book,new String[] {"bookname","price","booktype","id"});
}
public int delBook(Book book) throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, SQLException {
String sql="delete from book where id=?";
return super.executeUpdate(sql, book,new String[] {"id"});
}
public List<Book> queryBookList(Book book,PageBean pageBean) throws InstantiationException, IllegalAccessException, SQLException {
String sql="select *from book where 1=1";
String bookName=book.getBookname();
int id=book.getId();
if (StringUtils.isNotBlank(bookName)) {
sql += " and bookname like '%"+bookName+"%' ";
}
if (id != 0) {
sql+=" and id =" +id;
}
return super.queryBookList(sql, Book.class, pageBean);
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException, SQLException, NoSuchFieldException, SecurityException {
BookDao bookDao=new BookDao();
Book book=new Book();
PageBean pageBean = new PageBean();
book.setBookname("斗破苍穹");
book.setBooktype("玄幻");
book.setPrice(99f);
book.setId(89);
int editBook = bookDao.editBook(book);
System.out.println(editBook);
}
}
BookAction
package com.zhouzhuolin.mvc.action;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhouzhuolin.mvc.dao.BookDao;
import com.zhouzhuolin.mvc.entity.Book;
import com.zhouzhuolin.mvc.framework.DispatcherAction;
import com.zhouzhuolin.mvc.framework.DriverModel;
import com.zhouzhuolin.mvc.util.PageBean;
public class BookAction extends DispatcherAction implements DriverModel<Book> {
private static final long serialVersionUID = -4460537101055622972L;
private BookDao bookDao= new BookDao();
private Book book=new Book();
@Override
public Book getModel() {
return book;
}
public String queryBookPager(HttpServletRequest req,HttpServletResponse resp) throws InstantiationException, IllegalAccessException, SQLException {
PageBean pageBean =new PageBean();
pageBean.setRequest(req);
List<Book> List = bookDao.queryBookList(book, pageBean);
req.getSession().setAttribute("list", List);
req.getSession().setAttribute("pageBean", pageBean);
return "succes";
}
public String addBook(HttpServletRequest req,HttpServletResponse resp) throws InstantiationException, IllegalAccessException, SQLException, NoSuchFieldException, SecurityException {
bookDao.addBook(book);
return "list";
}
public String delBook(HttpServletRequest req,HttpServletResponse resp) throws InstantiationException, IllegalAccessException, SQLException, NoSuchFieldException, SecurityException {
bookDao.delBook(book);
return "list";
}
public String editBook(HttpServletRequest req,HttpServletResponse resp) throws InstantiationException, IllegalAccessException, SQLException {
if (book.getId()==0) {
System.out.println("执行添加逻辑");
}else {
Book b = this.bookDao.queryBookList(book, null).get(0);
req.getSession().setAttribute("book", b);
}
return "edit";
}
public String upBook(HttpServletRequest req,HttpServletResponse resp) throws InstantiationException, IllegalAccessException, NoSuchFieldException, SecurityException, SQLException {
bookDao.editBook(book);
return "list";
}
}
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>
<action type="com.zhouzhuolin.mvc.action.AddAction" path="/addAction">
<forward name="rs" path="/rs.jsp" redirect="false"/>
</action>
<action type="com.zhouzhuolin.mvc.action.CalAction" path="/calAction">
<forward name="rs" path="/rs.jsp" redirect="false"/>
</action>
<action type="com.zhouzhuolin.mvc.action.BookAction" path="/bookAction">
<forward name="succes" path="/index.jsp" redirect="false"/>
<forward name="edit" path="/addBook.jsp" redirect="false"/>
<forward name="list" path="/bookAction.action?methodName=queryBookPager" redirect="true"/>
</action>
</config>
分页标签
package com.zhouzhuolin.mvc.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.zhouzhuolin.mvc.util.PageBean;
public class PaginationTag extends BodyTagSupport{
private static final long serialVersionUID = 6425800140813236136L;
public PaginationTag() {
}
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.println(toHTML());
} catch (IOException e) {
e.printStackTrace();
}
return EVAL_BODY_INCLUDE;
}
public String toHTML() {
if (null==pageBean||!pageBean.isPagination())
return "";
StringBuffer sb=new StringBuffer();
sb.append("<form id=\"pageBeanForm\" action=\""+pageBean.getUri()+"\" method=\"post\">");
sb.append("<input type=\"hidden\" name=\"page\">");
Map<String, String[]> map = pageBean.getMap();
Set<Entry<String, String[]>> entrySet = map.entrySet();
for (Entry<String, String[]> entry : entrySet) {
String name=entry.getKey();
if ("page".equals(name)) {
continue;
}
String[] values=entry.getValue();
for (String value : values) {
sb.append("<input type='hidden' name='"+name+"' value='"+value+"'>");
}
}
sb.append("<div style=\"white:100%;height: 40px;line-height: 30px;text-align:right; \">");
sb.append("第"+pageBean.getPage()+"页/共"+pageBean.getMaxpager()+"页 ");
sb.append("每页"+pageBean.getRows()+"条数据/总共"+pageBean.getTotal()+"条记录 ");
sb.append("<a href=\"javascript:gotoPager(1)\">首页</a> ");
sb.append("<a href=\"javascript:gotoPager("+pageBean.getProivousPager()+")\">上一页</a> ");
sb.append("<a href=\"javascript:gotoPager("+pageBean.getNextPager()+")\">下一页</a> ");
sb.append("<a href=\"javascript:gotoPager("+pageBean.getMaxpager()+")\">末页</a> ");
sb.append("<input type=\"text\" id=\"skipPage\" style=\"width: 30px;\">");
sb.append("<input type=\"button\" value=\"GO\" οnclick=\"skipPager()\">");
sb.append("</div></form>");
sb.append("<script type=\"text/javascript\">function gotoPager(page) {\r\n" +
" document.getElementById(\"pageBeanForm\").page.value=page;\r\n" +
" document.getElementById(\"pageBeanForm\").submit();\r\n" +
" }");
sb.append("function skipPager() {\r\n" +
" var skipPager=document.getElementById(\"skipPage\").value;\r\n" +
" if (isNaN(skipPager)||skipPager<1||skipPager>"+pageBean.getMaxpager()+") {\r\n" +
" alert('请输入1~"+pageBean.getMaxpager()+"的数字');\r\n" +
" return false;\r\n" +
" }\r\n" +
" gotoPager(skipPager);\r\n" +
" }</script>");
return sb.toString();
}
}
具体的web层可以去点一下链接查看
web层具体类容
主页
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="z" uri="/zhouzhuolin" %>
<!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>
<!-- <script type="text/javascript">
function gotoPager(page) {
document.getElementById("pageBeanForm").page.value=page;
document.getElementById("pageBeanForm").submit();
}
function skipPager(maxpage) {
var skipPager=document.getElementById("skipPage").value;
if (isNaN(skipPager)||skipPager<1||skipPager>maxpage) {
alert('请输入1~'+maxpage+'的数字');
return false;
}
gotoPager(skipPager);
}
</script> -->
<body>
<form action="bookAction.action" method="post">
<label>书本名称</label><input type="text" name="bookname">
<input type="submit" name="methodName:queryBookPager" value="搜索">
</form>
<a href="addBook.jsp">新增</a>
<table width="100%" border="1" cellpadding="0" cellspacing="0">
<tr>
<td>编号</td>
<td>书名</td>
<td>价格</td>
<td>类型</td>
<td>操作</td>
</tr>
<c:forEach var="book" items="${list }">
<tr>
<td>${book.id }</td>
<td>${book.bookname }</td>
<td>${book.price }</td>
<td>${book.booktype }</td>
<td>
<a href="bookAction.action?methodName=delBook&id=${book.id }">删除</a>
<a href="bookAction.action?methodName=editBook&id=${book.id }">修改</a>
</td>
</tr>
</c:forEach>
</table>
<%-- <label>${pageBean}</label>
<form id="pageBeanForm" action="${pageBean.uri }" method="post">
<input type="hidden" name="page">
<div style="white:100%;height: 40px;line-height: 30px;text-align:right; ">
第${pageBean.page}页/共${pageBean.getMaxpager()}页 每页${pageBean.rows}条数据/总共${pageBean.total}条记录
<a href="javascript:gotoPager(1)">首页</a>
<a href="javascript:gotoPager(${pageBean.getProivousPager() })">上一页</a>
<a href="javascript:gotoPager(${pageBean.getNextPager() })">下一页</a>
<a href="javascript:gotoPager(${pageBean.getMaxpager() })">末页</a>
<input type="text" id="skipPage" style="width: 30px;">
<input type="button" value="GO" onclick="skipPager(${pageBean.getMaxpager() })">
</div>
</form> --%>
<z:pagination pageBean="${pageBean }"/>
</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>Insert title here</title>
</head>
<body>
<form action="bookAction.action" method="get">
<input type="hidden" name="id" value="${book.id }">
书本名字:<input type="text" name="bookname" value="${book.bookname }"><br>
书本类型:<input type="text" name="booktype" value="${book.booktype }"><br>
书本价格:<input type="text" name="price" value="${book.price }"><br>
<%-- 书本:<input type="text" name="price" value="methodName:${book.bookname == null ? 'add' : 'edit' }"><br>
methodName:add --%>
<input type="submit" name="methodName:${book.bookname == null ? 'addBook' : 'upBook' }" value="提交">
</form>
</body>
</html>