自定义MVC框架(实现增删改查)

目录

一.环境配置

1.1、导入jar包

2.2.将分页标签相关文件、及相关助手类导入

三.通用增删改查

四.后台代码

 五.前端代码

这篇 自定义MVC框架(实现增删改查)就介绍到这里了,欢迎大佬来提建议哦!!!!


一.环境配置

1.1、导入jar包

首先将我们前面写的代码打成一个jar包然后导入我们的项目:

 自定义MVC框架(实现增删改查)_第1张图片

其次把它导成jar包:

自定义MVC框架(实现增删改查)_第2张图片 

自定义MVC框架(实现增删改查)_第3张图片 

就是这样一个图形你就成功了

 

最后把它导入项目中

自定义MVC框架(实现增删改查)_第4张图片 

好啦第一步就成功了。接下来我们就 

2.2.将分页标签相关文件、及相关助手类导入

 将之前util包导入进来

BaseDao

package com.junlinyi.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.junlinyi.util.DBAccess;
import com.junlinyi.util.PageBean;
import com.junlinyi.util.StringUtils;

/**
 * 所有Dao层的父类
 * 	BookDao
 * 	UserDao
 * 	OrderDao
 * 	...
 * @author Administrator
 *
 * @param 
 */
public class BaseDao {
	/**
	 * 通用的增删改方法
	 * @param sql   增删改sql
	 * @param t		sql中的表对应的实体类
	 * @param attrs  实体类对应的属性
	 * @return
	 * @throws Exception
	 */
	public int executeUpdate(String sql,T t,String[] attrs) throws Exception {
		Connection con = DBAccess.getConnection();
		PreparedStatement ps = con.prepareStatement(sql);
		for (int i = 0; i < attrs.length; i++) {
			Field f = t.getClass().getDeclaredField(attrs[i]);
			f.setAccessible(true);
			ps.setObject(i+1,f.get(t));
		}
		return ps.executeUpdate();
	}
	
	
	/**
	 * 通用分页查询
	 * @param sql
	 * @param clz
	 * @return
	 * @throws Exception
	 */
	public List executeQuery(String sql,Class clz,PageBean pageBean) throws Exception{
		List list = new ArrayList();
		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();
	}
}

DBAccess

package com.junlinyi.util;

import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

/**
 * 提供了一组获得或关闭数据库对象的方法
 * 
 */
public class DBAccess {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;

	static {// 静态块执行一次,加载 驱动一次
		try {
			InputStream is = DBAccess.class
					.getResourceAsStream("config.properties");

			Properties properties = new Properties();
			properties.load(is);

			driver = properties.getProperty("driver");
			url = properties.getProperty("url");
			user = properties.getProperty("user");
			password = properties.getProperty("pwd");

			Class.forName(driver);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	/**
	 * 获得数据连接对象
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		try {
			Connection conn = DriverManager.getConnection(url, user, password);
			return conn;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		}
	}

	public static void close(ResultSet rs) {
		if (null != rs) {
			try {
				rs.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Statement stmt) {
		if (null != stmt) {
			try {
				stmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Connection conn) {
		if (null != conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
	}

	public static void close(Connection conn, Statement stmt, ResultSet rs) {
		close(rs);
		close(stmt);
		close(conn);
	}

	public static boolean isOracle() {
		return "oracle.jdbc.driver.OracleDriver".equals(driver);
	}

	public static boolean isSQLServer() {
		return "com.microsoft.sqlserver.jdbc.SQLServerDriver".equals(driver);
	}
	
	public static boolean isMysql() {
		return "com.mysql.cj.jdbc.Driver".equals(driver);
	}

	public static void main(String[] args) {
		Connection conn = DBAccess.getConnection();
		System.out.println(conn);
		DBAccess.close(conn);
		System.out.println("isOracle:" + isOracle());
		System.out.println("isSQLServer:" + isSQLServer());
		System.out.println("isMysql:" + isMysql());
		System.out.println("数据库连接(关闭)成功");
	}
}

 EncodingFiter

package com.junlinyi.util;

import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 中文乱码处理
 * 
 */
@WebFilter("*.action")
public class EncodingFiter implements Filter {

	private String encoding = "UTF-8";// 默认字符集

	public EncodingFiter() {
		super();
	}

	public void destroy() {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		// 中文处理必须放到 chain.doFilter(request, response)方法前面
		res.setContentType("text/html;charset=" + this.encoding);
		if (req.getMethod().equalsIgnoreCase("post")) {
			req.setCharacterEncoding(this.encoding);
		} else {
			Map map = req.getParameterMap();// 保存所有参数名=参数值(数组)的Map集合
			Set set = map.keySet();// 取出所有参数名
			Iterator it = set.iterator();
			while (it.hasNext()) {
				String name = (String) it.next();
				String[] values = (String[]) map.get(name);// 取出参数值[注:参数值为一个数组]
				for (int i = 0; i < values.length; i++) {
					values[i] = new String(values[i].getBytes("ISO-8859-1"),
							this.encoding);
				}
			}
		}

		chain.doFilter(request, response);
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		String s = filterConfig.getInitParameter("encoding");// 读取web.xml文件中配置的字符集
		if (null != s && !s.trim().equals("")) {
			this.encoding = s.trim();
		}
	}

}

 PageBean :分页工具类

package com.junlinyi.util;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

/**
 * 分页工具类
 *
 */
public class PageBean {

	private int page = 1;// 页码

	private int rows = 10;// 页大小

	private int total = 0;// 总记录数

	private boolean pagination = true;// 是否分页
	
	private String url; //保存上一次请求的URL
	
	private Map paramMap = new HashMap<>();// 保存上一次请求的参数
	
	/**
	 * 初始化pagebean的,保存上一次请求的重要参数
	 * @param req
	 */
	public void setRequest(HttpServletRequest req) {
//		1.1	需要保存上一次请求的URL
		this.setUrl(req.getRequestURL().toString());
//		1.2	需要保存上一次请求的参数	bname、price
		this.setParamMap(req.getParameterMap());
//		1.3	需要保存上一次请求的分页设置	pagination
		this.setPagination(req.getParameter("pagination"));
//		1.4	需要保存上一次请求的展示条目数
		this.setRows(req.getParameter("rows"));
//		1.5  初始化请求的页码	page
		this.setPage(req.getParameter("page"));
	}
	
	public void setPage(String page) {
		if(StringUtils.isNotBlank(page))
			this.setPage(Integer.valueOf(page));
	}

	public void setRows(String rows) {
		if(StringUtils.isNotBlank(rows))
			this.setRows(Integer.valueOf(rows));
	}

	public void setPagination(String pagination) {
//		只有在前台jsp填写了pagination=false,才代表不分页
		if(StringUtils.isNotBlank(pagination))
			this.setPagination(!"false".equals(pagination));
	}


	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Map getParamMap() {
		return paramMap;
	}

	public void setParamMap(Map paramMap) {
		this.paramMap = paramMap;
	}



	public PageBean() {
		super();
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}

	public void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}

	public boolean isPagination() {
		return pagination;
	}

	public void setPagination(boolean pagination) {
		this.pagination = pagination;
	}

	/**
	 * 获得起始记录的下标
	 * 
	 * @return
	 */
	public int getStartIndex() {
		return (this.page - 1) * this.rows;
	}
	
	/**
	 * 最大页
	 * @return
	 */
	public int maxPage() {
//		total % rows == 0 ? total / rows : total / rows +1
		return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1;
	}
	
	/**
	 * 下一页
	 * @return
	 */
	public int nextPage() {
//		如果当前页小于最大页,那就下一页为当前页+1;如果不小于,说明当前页就是最大页,那就无需+1
		return this.page < this.maxPage() ? this.page + 1 : this.page;
	}
	
	/**
	 * 上一页
	 * @return
	 */
	public int previousPage() {
		return this.page > 1 ? this.page - 1 : this.page;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
	}

}

 StringUtils

package com.junlinyi.util;

public class StringUtils {
	// 私有的构造方法,保护此类不能在外部实例化
	private StringUtils() {
	}

	/**
	 * 如果字符串等于null或去空格后等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isBlank(String s) {
		boolean b = false;
		if (null == s || s.trim().equals("")) {
			b = true;
		}
		return b;
	}
	
	/**
	 * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
	 * 
	 * @param s
	 * @return
	 */
	public static boolean isNotBlank(String s) {
		return !isBlank(s);
	}

}

 数据库连接

#oracle9i
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@localhost:1521:ora9
#user=test
#pwd=test


#sql2005
#driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#url=jdbc:sqlserver://localhost:1423;DatabaseName=test
#user=sa
#pwd=sa


#sql2000
#driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
#url=jdbc:microsoft:sqlserver://localhost:1433;databaseName=unit6DB
#user=sa
#pwd=888888

#mysql5
#driver=com.mysql.jdbc.Driver
#url=jdbc:mysql://127.0.0.1:3306/mybatis_ssm?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT
#user=mybatis_ssm
#pwd=xiaoli

#mysql8
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/mybatis_ssm?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT&useSSL=true
user=root
pwd=123456



 PageTag

package com.junlinyi.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.junlinyi.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("
"); sb.append(" "); // 上一次请求的参数 Map paramMap = pageBean.getParamMap(); if(paramMap != null && paramMap.size() > 0) { Set> entrySet = paramMap.entrySet(); for (Entry entry : entrySet) { // 参数名 String key = entry.getKey(); // 参数值 for (String value : entry.getValue()) { // 上一次请求的参数,再一次组装成了新的Form表单 // 注意:page参数每次都会提交,我们需要避免 if(!"page".equals(key)) { sb.append(" "); } } } } sb.append(""); // 分页条 sb.append("
    "); sb.append("
  • 首页
  • "); sb.append("
  • <
  • ");// less than 小于号 // sb.append("
  • 1
  • "); // sb.append("
  • 2
  • "); sb.append("
  • "+pageBean.getPage()+"
  • "); sb.append("
  • >
  • "); sb.append("
  • 尾页
  • "); sb.append("
  • 到第
  • "); sb.append("
  • 确定
  • "); sb.append("
  • 共"+pageBean.getTotal()+"条
  • "); sb.append("
"); // 分页执行的JS代码 sb.append(""); return sb.toString(); } }

 最后配置框架配置



  JunLunYi_MVC_crud
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
  
  	mvc
  	com.zking.framework.DispatchServlet
  	
  		configurationLocation
  		/mvc.xml
  	
  
  
  	mvc
  	*.action
  

三.通用增删改查

发现前面写增删改查的代码很繁琐而且有待改进。可以利用自定义MVC框架来做到简化冗余代码的同时实现与之相同的功能。这是用MVC框架来实现的代码(以书籍管理系统为例),如下: 

 一样的建一个书籍类:

package com.junlinyi.entity;
/**
 *实体类
 * @author: 君临沂
 *
 */
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;
		}
		
		public Book() {
			// TODO Auto-generated constructor stub
		}
		public Book(int bid, String bname, float price) {
			super();
			this.bid = bid;
			this.bname = bname;
			this.price = price;
		}
		@Override
		public String toString() {
			return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
		}
		
		
		
}

再建dao类 :写增删改查方法

package com.junlinyi.dao;

import java.util.List;

import com.junlinyi.entity.Book;
import com.junlinyi.util.BaseDao;
import com.junlinyi.util.PageBean;
import com.junlinyi.util.StringUtils;

/**
 * 
 * @author: 君临沂
 *
 */
public class BookDao extends BaseDao {
//	查询
		public List 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+"%'";
			}
//			bod==0 意味着前台没有传递bid值
			if(bid !=0) {
				sql +="and bid ="+ bid;
			}
			return super.executeQuery(sql, Book.class, pageBean);
		}
//		增加
		public int add(Book book) throws Exception {
			String sql="insert into t_mvc_book values(?,?,?)";
			return super.executeUpdate(sql,book,new String[] {"bid","bname","price"});
		}
		
//		删除
		public int del(Book book) throws Exception {
			String sql="delete from t_mvc_book where bid=?";
			return super.executeUpdate(sql,book,new String[] {"bid"});
		}
		
//		修改
		public int upd(Book book) throws Exception {
			String sql="update t_mvc_book set bname=?,price=? where bid=?";
			return super.executeUpdate(sql,book,new String[] {"bname","price","bid"});
		}
		
		
}

 测试:

package com.junlinyi.dao;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.Test;

import com.junlinyi.entity.Book;
import com.junlinyi.util.PageBean;

public class BookDaoTest {
	private BookDao bookDao=new BookDao();

	@Test
	public void testList() throws Exception {
		Book book=new Book();
		book.setBname("圣墟");
		PageBean pageBean=new PageBean();
		pageBean.setPage(3);
		List list = bookDao.list(book,pageBean);
		for (Book b : list) {
			System.out.println(b);
		}
	}

	@Test
	public void testAdd() throws Exception {
		Book book=new Book(52,"圣墟",99);
		bookDao.add(book);
	}

	@Test
	public void testDel() throws Exception {
		Book book=new Book();
		book.setBid(52);
		bookDao.del(book);
	}

	@Test
	public void testUpd() throws Exception {
		Book book=new Book(52,"圣墟第52章",90);
		bookDao.upd(book);
	}

}

 方法代码写完我们来测试一下增删改查

自定义MVC框架(实现增删改查)_第5张图片

自定义MVC框架(实现增删改查)_第6张图片 

 自定义MVC框架(实现增删改查)_第7张图片

 自定义MVC框架(实现增删改查)_第8张图片

通过测试增删改方法没有问题,接下来我们下一步操作。

四.后台代码

接下来我们用我们简单的布局在浏览器中实现增删改查

BookAction

package com.junlinyi.web;

import java.util.List;

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

import com.junlinyi.dao.BookDao;
import com.junlinyi.entity.Book;
import com.junlinyi.util.PageBean;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;

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

	// 查询 booklist.jsp
	public String list(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		PageBean pageBean = new PageBean();
		// 初始化
		pageBean.setRequest(req);
		List list = bookDao.list(book, pageBean);
		req.setAttribute("list", list);
		req.setAttribute("PageBean", pageBean);
		return "list";
	}

	// 编辑页面跳转 bookUpd.jsp
	public String toUpd(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		if (book.getBid() != 0) {
			List list = bookDao.list(book, null);
			req.setAttribute("b", list.get(0));
		}
		return "toUpd";
	}

	// 增加
	public String add(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		bookDao.add(book);
		return "addList";
	}
	// 删除
	public String del(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		bookDao.del(book);
		return "delList";
	}
	// 修改
	public String upd(HttpServletRequest req, HttpServletResponse resp) throws Exception {
		bookDao.upd(book);
		return "updList";
	}

	@Override
	public Book getModel() {

		return book;
	}

}

将BookAction配置到mvc.xmml中



	
	
		
		
		
	
	
	

 

 五.前端代码

cv我们之前写的BookList.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="http://www/JunLinYi/com" prefix="z"%>






书籍列表



	${pageBean }
	
增加
书籍ID 书籍名 价格 操作
${b.bid } ${b.bname } ${b.price } 修改 删除

bookUpd.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>




书籍编辑页面(修改/增加共用)



		编号:
名称:
价格:

实现图:

 

这篇 自定义MVC框架(实现增删改查)就介绍到这里了,欢迎大佬来提建议哦!!!!

 

你可能感兴趣的:(mvc)