mvc(3)

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> {
	/**
	 * 
	 * @param sql				传入的sql语句
	 * @param clz				传入的对象
	 * @param pageBean			分页
	 * @return
	 * @throws SQLException
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public List<T> queryBookList(String sql,Class<?> clz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException {
		Connection con=DBAccess.getConnection(); 
		PreparedStatement ps=null;
		ResultSet rs=null;
//		如果pageBean不等于空 并且 允许分页 则执行分页代码块
		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()) {
//			list.add(new Book(rs.getInt("id"), rs.getString("bookname"), rs.getFloat("price"), rs.getString("booktype")));
//			通过反射机制实例化 并且赋值
			t=(T) clz.newInstance();
			Field[] fields = clz.getDeclaredFields();
			for (Field field : fields) {
				field.setAccessible(true);
//				getObject 因为不知道传过来是什么值 所以写个Object代替 
				field.set(t, rs.getObject(field.getName()));
			}
			list.add(t);
		}
		DBAccess.close(con, ps, rs);
		return list;
		
	}
	
//	获取总纪录数的sql语句
	public String getCountSql(String sql) {
		return "select count(*) from ("+sql+") t";
	}
//	获取分页数据的sql语句
	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);
//		ps.setString(1, book.getBookname());
//		ps.setFloat(2, book.getPrice());
//		ps.setString(3, book.getBooktype());
		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();
//		book.setBookname("1");
		PageBean pageBean = new PageBean();
//		pageBean.setPage(2);
//		pageBean.setRows(10);
//		pageBean.setPagination(false);
//		int total = pageBean.getTotal();
		book.setBookname("斗破苍穹");
		book.setBooktype("玄幻");
		book.setPrice(99f);
		book.setId(89);
		int editBook = bookDao.editBook(book);
//		int delBook = bookDao.delBook(book);
//		int addBook = bookDao.addBook(book);
		System.out.println(editBook);
//		List<Book> queryBookList = bookDao.queryBookList(book, pageBean);
//		for (Book book2 : queryBookList) {
//			System.out.println(book2);
//		}
		
	}

}

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标签:可以包含0~N个action标签
	-->
<config>
	<!--
		action标签:可以饱含0~N个forward标签
		path:以/开头的字符串,并且值必须唯一 非空
		type:字符串,非空
	-->
	<!-- <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> -->
	
	
	<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) {
			// TODO Auto-generated catch block
			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) {
//			获取请求参数名,例如:name="bookname"
			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()+"页&nbsp;");
		sb.append("每页"+pageBean.getRows()+"条数据/总共"+pageBean.getTotal()+"条记录&nbsp;");
//		封装首页。上一页。下一页。末页方法
		sb.append("<a href=\"javascript:gotoPager(1)\">首页</a>&nbsp;");
		sb.append("<a href=\"javascript:gotoPager("+pageBean.getProivousPager()+")\">上一页</a>&nbsp;");
		sb.append("<a href=\"javascript:gotoPager("+pageBean.getNextPager()+")\">下一页</a>&nbsp;");
		sb.append("<a href=\"javascript:gotoPager("+pageBean.getMaxpager()+")\">末页</a>&nbsp;");
		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">&nbsp;
		<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>&nbsp;
					<a href="bookAction.action?methodName=editBook&id=${book.id }">修改</a>&nbsp;
				</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()}&nbsp;每页${pageBean.rows}条数据/总共${pageBean.total}条记录&nbsp;
			<a href="javascript:gotoPager(1)">首页</a>&nbsp;
			<a href="javascript:gotoPager(${pageBean.getProivousPager() })">上一页</a>&nbsp;
			<a href="javascript:gotoPager(${pageBean.getNextPager() })">下一页</a>&nbsp;
			<a href="javascript:gotoPager(${pageBean.getMaxpager() })">末页</a>&nbsp;
			<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>
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值