自定义MVC增删改查

本文介绍了如何自定义一个MVC框架并实现增删改查功能。首先,通过导出并引入jar包配置框架环境,接着编写和优化实体类及DAO方法,减少重复代码。然后,搭建前端界面,包括主界面和增改界面。在BookAction中完成逻辑,并配置mvc.xml解决重复提交问题。最后,展示了实现后的效果。
摘要由CSDN通过智能技术生成

目录

前言

一、配置自定义mvc框架环境

二、实体类、以及dao方法的编写和优化

三、前台的搭建

四、BookAction的完成、完成mvc.xml的配置和重复提交表单问题

五、效果


前言

今日分享的是自定义mvc的增删改,并将其优化成通用的


提示:以下是本篇文章正文内容,下面案例可供参考

一、配置自定义mvc框架环境

1.将我们上次写的框架打成jar包,然后导入新工程,并且把框架的依赖jar包导入进去

①选中我们之前写的framework,右键选中Export...

②输入框中输入java,然后选中 JAR file,点击next

③选择保存地址,然后Finsih即可

④将之前写的分页标签相关文件、及相关助手类导入

 ⑤将框架的配置文件添加、以及web.xml的配置

 注意:要将我们打出来的jar包所需要的包也导入项目中

 web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>J2EE_crud</display-name>
  <servlet>
	<servlet-name>mvc</servlet-name>  
  	<servlet-class>com.mgy.framework.DispatcherServlet</servlet-class>
  	<init-param>
  		<param-name>configLocation</param-name>
  		<param-value>/asd.xml</param-value>
  	</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>mvc</servlet-name>
	<url-pattern>*.action</url-pattern>
  </servlet-mapping>
</web-app>

二、实体类、以及dao方法的编写和优化

实体类(书籍类):

package com.mgy.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() {
		super();
	}

	public Book(int bid, String bname, float price) {
		super();
		this.bid = bid;
		this.bname = bname;
		this.price = price;
	}
	
	
}

基础的dao方法:

package com.mgy.dao;

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

import com.mgy.entity.Book;
import com.mgy.util.BaseDao;
import com.mgy.util.DBAccess;
import com.mgy.util.PageBean;
import com.mgy.util.StringUtils;

public class BookDao extends BaseDao<Book>{
	//查询
	public List<Book> list(Book book,PageBean pageBean) throws Exception{
		String sql="select * from t_mvc_book where 1=1";
		String bname=book.getBname();
		if(StringUtils.isNotBlank(bname)) {
			sql+=" and bname like '%"+bname+"%'";
		}
		int bid=book.getBid();
		//前台jsp传递到后台,只要传了就有值
		if(bid!=0) {
			sql+=" and bid="+bid;
		}
		return super.list(sql, pageBean, rs ->{
			List<Book> list=new ArrayList<>();
			try {
				while(rs.next()) {
					list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return list;
		});
	}
	
	//增加
	public int add(Book book) throws Exception {
		Connection con = DBAccess.getConnection();
		String sql="insert into t_mvc_book values(?,?,?)";
		PreparedStatement ps = con.prepareStatement(sql);
		ps.setObject(1, book.getBid());
		ps.setObject(2, book.getBname());
		ps.setObject(3, book.getPrice());
		return ps.executeUpdate();
	}
	
	//删
	public int del(Book book)throws Exception {
		Connection con = DBAccess.getConnection();
		String sql = "delete from t_mvc_book where bid=?";
		PreparedStatement pst = con.prepareStatement(sql);
		pst.setObject(1, book.getBid());
		return pst.executeUpdate();
	}
	
	
	//改
	public int edit(Book book)throws Exception{
		Connection con = DBAccess.getConnection();
		String sql = "update  t_mvc_book set bname=?,price=? where bid=?";
		PreparedStatement pst = con.prepareStatement(sql);
		pst.setObject(1, book.getBname());
		pst.setObject(2, book.getPrice());
		pst.setObject(3, book.getBid());
		return pst.executeUpdate();
	}
	
}

我们可以发现增删改中都有重复的代码块,所以我们在BaseDao中添加以下方法

	public int executeUpdate(String sql,T t,String[] attrs ) throws Exception{
		Connection con = DBAccess.getConnection();
		PreparedStatement pst = con.prepareStatement(sql);
		//将t的某一个属性对应的值加到pst对象中
		for (int i = 0; i < attrs.length; i++) {
			Field f = t.getClass().getDeclaredField(attrs[i]);
			f.setAccessible(true);
			pst.setObject(i+1, f.get(t));
		}
//		pst.setObject(1, book.getBid());
//		pst.setObject(2, book.getBname());
//		pst.setObject(3, book.getPrice());
		return pst.executeUpdate();
	
	}

通用增删改查:

package com.mgy.dao;

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

import com.mgy.entity.Book;
import com.mgy.util.BaseDao;
import com.mgy.util.DBAccess;
import com.mgy.util.PageBean;
import com.mgy.util.StringUtils;

public class BookDao extends BaseDao<Book>{
	//查询
	public List<Book> list(Book book,PageBean pageBean) throws Exception{
		String sql="select * from t_mvc_book where 1=1";
		String bname=book.getBname();
		if(StringUtils.isNotBlank(bname)) {
			sql+=" and bname like '%"+bname+"%'";
		}
		int bid=book.getBid();
		//前台jsp传递到后台,只要传了就有值
		if(bid!=0) {
			sql+=" and bid="+bid;
		}
		return super.list(sql, pageBean, rs ->{
			List<Book> list=new ArrayList<>();
			try {
				while(rs.next()) {
					list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price")));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return list;
		});
	}
	
	//增
	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 edit(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"});
	}
}

三、前台的搭建

主界面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.veryedu.cn"  prefix="z"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"  prefix="c"%>
<!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">
  <link href="css/bootstrap.css" rel="stylesheet">
<script type="text/javascript" src="js/bootstrap.js"></script> 
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css" rel="stylesheet">
<script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>

 <title>书籍列表</title>
<style type="text/css">
.page-item input {
	padding: 0;
	width: 40px;
	height: 100%;
	text-align: center;
	margin: 0 6px;
}

.page-item input, .page-item b {
	line-height: 38px;
	float: left;
	font-weight: 400;
}

.page-item.go-input {
	margin: 0 10px;
}
</style>
</head>
<!-- ${pageContext.request.contextPath } -->
<body>
<%-- <c:if test="${empty list }">
	<jsp:forward page="book/search"></jsp:forward>
</c:if> --%>
	<form class="form-inline"
		action="${pageContext.request.contextPath }/book.action?methodName=list" method="post">
		<div class="form-group mb-2">
			<input type="text" class="form-control-plaintext" name="bname"
				placeholder="请输入书籍名称">
		</div>
		<button type="submit" class="btn btn-primary mb-2">查询</button>
		<a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/book.action?methodName=preEdit">增加</a>
		
	</form>

	<table class="table table-striped ">
		<thead>
			<tr>
				<th scope="col">书籍ID</th>
				<th scope="col">书籍名</th>
				<th scope="col">价格</th>
				<th scope="col">操作</th>
			</tr>
		</thead>
		<tbody>
		<c:forEach items="${list }" var="b">
			<tr>
				<td>${b.bid }</td>
				<td>${b.bname }</td>
				<td>${b.price }</td>
				<td>
					<a href="${pageContext.request.contextPath }/book.action?methodName=preEdit&bid=${b.bid }">修改</a>
					<a href="${pageContext.request.contextPath }/book.action?methodName=del&bid=${b.bid }">删除</a>
				
				</td>
			</tr>
		</c:forEach>
		

		</tbody>
	</table>
	
	<z:page pageBean="${pageBean }"></z:page>


</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 = "${pageContext.request.contextPath }/book.action?methodName=${empty b ? 'add' : 'edit'}" method="post" >
		bid:<input type="text" name="bid" value="${b.bid }"><br>
		bname:<input type="text" name="bname" value="${b.bname }"><br>
		price:<input type="text" name="price" value="${b.price }"><br>
		<input type="submit">
	
	</form>


</body>
</html>

四、BookAction的完成、完成mvc.xml的配置和重复提交表单问题

mvc.xml:

<?xml version="1.0" encoding="UTF-8"?>
<config>
	<action path="/book" type="com.mgy.web.BookAction">
		<forward name="list" path="/index.jsp" redirect="false" />
		<forward name="toEdit" path="/bookEdit.jsp" redirect="false" />
		<forward name="toList" path="/book.action?methodName=list" redirect="true" />
	</action>
</config>

BookAction:

package com.mgy.web;

import java.util.List;

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

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

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

	//增
	public String add(HttpServletRequest request, HttpServletResponse response) {
		
		try {
			bookDao.add(book);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//toList代表跳到查询页面
		return "toList";
	}
	
	
	//删
	public String del(HttpServletRequest request, HttpServletResponse response) {
		
		try {
			bookDao.del(book);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//toList代表跳到查询页面
		return "toList";
	}
	
	
	//改
	public String edit(HttpServletRequest request, HttpServletResponse response) {
		
		try {
			bookDao.edit(book);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//toList代表跳到查询页面
		return "toList";
	}
	
	
	//查
	public String list(HttpServletRequest request, HttpServletResponse response) {
		
		try {
			PageBean pageBean = new PageBean();
			pageBean.setRequest(request);
			List<Book> list = bookDao.list(book,pageBean);
			request.setAttribute("list", list);
			request.setAttribute("pageBean", pageBean);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//执行查询展示
		return "list";
	}
	
	//跳转到新增/修改界面
	public String preEdit(HttpServletRequest request, HttpServletResponse response) {
		
		try {
			int bid = book.getBid();
			if(bid!=0) {
				//传递bid到后台,有且只能查出一条数据,那也就意味着list集合中只要一条
				List<Book> list = bookDao.list(book, null);
				request.setAttribute("b", list.get(0));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		//toList代表跳到查询页面
		return "toEdit";
	}
}

五、效果

MVC模式的实现对数据库的增删改查 部分代码: package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import common.DBConnection; import bean.Contact; public class ContactDAO { public List getAllContact() throws Exception{ Connection conn=DBConnection.getConntion(); PreparedStatement ps=conn.prepareStatement("select * from Contact"); ResultSet rs=ps.executeQuery(); List list = new ArrayList(); while(rs.next()){ int id = rs.getInt("id"); String name = rs.getString("name"); String phone = rs.getString("phone"); String address = rs.getString("address"); Contact c = new Contact(); c.setId(id); c.setName(name); c.setPhone(phone); c.setAddress(address); list.add(c); } rs.close(); ps.close(); conn.close(); return list; } public void addContact(String name,String phone,String address) throws Exception{ String sql = "insert into contact(id,name,phone,address) values(seq_contact.nextval,?,?,?)"; Connection con = DBConnection.getConntion(); PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setString(1, name); pstmt.setString(2, phone); pstmt.setString(3, address); pstmt.executeUpdate(); } public void delContact(int id) throws Exception{ String sql = "delete from contact where id=?"; Connection con = DBConnection.getConntion(); PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setInt(1, id); pstmt.executeUpdate(); } public Contact getContactById(int id) throws Exception{ String sql = "select * from Contact where id=?"; Connection con = DBConnection.getConntion(); PreparedStatement pstmt = con.prepareStatement(sql); pstmt.setInt(1, id); ResultSet rs = pstmt.executeQuery(); Contact c = null; while(rs.next()){ // int id = rs.getInt("id"); String name=rs.getString("name"); String p
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值