mvc3优化

MVC3优化

主要是把之前所学的通用分页和mvc进行增删改查

首先导入7个ar包:
在这里插入图片描述
然后分别把辅助工具类写好:

在这里插入图片描述

开始写个book实体类:

package com.xiaoyi.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();
	}

}

BookDao:

package com.xiaoyi.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import com.xiaoyi.entity.Book;
import com.xiaoyi.util.BaseDao;
import com.xiaoyi.util.PageBean;
import com.xiaoyi.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, "xxx", 56f);
		try {
			bookDao.del(book);
		} catch (IllegalArgumentException | IllegalAccessException | SQLException e) {
			e.printStackTrace();
		}
		
	}
}

BaseDao:

package com.xiaoyi.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;


/**
 * 用来处理所有表的通用的增删改查的基类
 * 
 * 查询指的是:通用的分页查询
 * @author Administrator
 *
 * @param <T>
 */
public class BaseDao<T> {
	/**
	 * 
	 * @param sql	可能不同的表,那么意味着sql是变化的,那么它是从子类处理好再传递到父类
	 * @param clz	需要返回不同的对象集合	Book.class/Order.class
	 * @param pageBean	可能要分页
	 * @return
	 * @throws SQLException
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public List<T> executeQuery(String sql,Class clz,PageBean pageBean) throws SQLException, InstantiationException, IllegalAccessException{
		List<T> list = new ArrayList<>();
		Connection con = DBAccess.getConnection();
		PreparedStatement pst = null;
		ResultSet rs = null;
		if(pageBean != null && pageBean.isPagination()) {
//			分页代码
			/*
			 * 1、分页是与pagebean中total,意味着需要查询数据库得到total赋值给pagebean
			 * 2、查询出符合条件的某一页的数据
			 */
//			select count(*) from (select * from t_mvc_book where bname like '%圣墟%') t;
			String countSql = getCountSql(sql);
			pst = con.prepareStatement(countSql);
			rs = pst.executeQuery();
			if(rs.next()) {
				pageBean.setTotal(rs.getObject(1).toString());
			}
			
//			select * from t_mvc_book where bname like '%圣墟%' limit 20,10
			String pageSql = getPageSql(sql,pageBean);
			pst = con.prepareStatement(pageSql);
			rs = pst.executeQuery();
			
		}else {
//			不分页代码
			pst = con.prepareStatement(sql);
			rs = pst.executeQuery();
		}
		
		T t = null;
		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);
		}
		DBAccess.close(con, pst, rs);
		return list;
	}

	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";
	}
	
	/**
	 * 
	 * @param sql	增删改的sql语句
	 * @param attrs	代表了sql语句中的问号	"bname","price","bid"
	 * @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 pst = con.prepareStatement(sql);
		Field field = null;
		for (int i = 0; i < attrs.length; i++) {
			try {
				field = t.getClass().getDeclaredField(attrs[i]);
				field.setAccessible(true);
				pst.setObject(i+1, field.get(t));
			} catch (NoSuchFieldException | SecurityException e) {
				e.printStackTrace();
			}
		}
		int num = pst.executeUpdate();
		DBAccess.close(con, pst, null);
		return num;
	}
	
}

BookAction跳转新增修改页面:

package com.xiaoyi.web;

import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.xiaoyi.dao.BookDao;
import com.xiaoyi.entity.Book;
import com.xiaoyi.framework.ActionSupport;
import com.xiaoyi.framework.ModelDriven;
import com.xiaoyi.util.PageBean;


public class BookAction extends ActionSupport implements ModelDriven<Book> {
	private Book book = new Book();
	private BookDao bookDao = new BookDao();

	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) {
			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) {
				e.printStackTrace();
			}
		}
		return "edit";
	}

	public String add(HttpServletRequest req, HttpServletResponse resp) {
		try {
			this.bookDao.add(book);
		} catch (IllegalArgumentException | IllegalAccessException | SQLException e) {
			e.printStackTrace();
		}
		return "toList";
	}

	public String edit(HttpServletRequest req, HttpServletResponse resp) {
		try {
			this.bookDao.edit(book);
		} catch (IllegalArgumentException | IllegalAccessException | SQLException e) {
			e.printStackTrace();
		}
		return "toList";

	}
	
	public String del(HttpServletRequest req, HttpServletResponse resp) {
		try {
			this.bookDao.del(book);
		} catch (IllegalArgumentException | IllegalAccessException | SQLException e) {
			e.printStackTrace();
		}
		return "toList";

	}

	@Override
	public Book getModel() {
		return book;
	}
}

配置mvc文件:

<?xml version="1.0" encoding="UTF-8"?>
<config>
	<!-- <action path="/cal_add" type="com.zking.web.AddCalAction"> -->
	<!-- <forward name="rs" path="/rs.jsp" redirect="false" /> -->
	<!-- </action> -->
	<!-- <action path="/cal_del" type="com.zking.web.DelCalAction"> -->
	<!-- <forward name="rs" path="/rs.jsp" redirect="false" /> -->
	<!-- </action> -->
	<action path="/cal" type="com.xiaoyi.web.CalAction">
		<forward name="rs" path="/rs.jsp" redirect="false" />
	</action>
	
	<action path="/book" type="com.xiaoyi.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>

bookEdit 书籍编辑页面:

<%@ 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>

bookList 书籍主页:

<%@ 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">
<title>书籍主页</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>&nbsp;&nbsp;
				<a href="${pageContext.request.contextPath}/book.action?methodName=del&&bid=${b.bid }">删除</a>
				</td>
			</tr>
		</c:forEach>
	</table>
	
	<z:page pageBean="${pageBean }"></z:page>

</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值