自定义mvc的增删改查

目录

1.搭建自定义mvc框架环境

2.基础的增删改

 3.通用的增删改查

4.查询删除及重复表单提交的问题及修改


1.搭建自定义mvc框架环境

 xml配置:如下

<?xml version="1.0" encoding="UTF-8"?>
<config>
	
	

	<action path="/permission" type="com.zking.web.PermissionAction">
		<forward name="list" path="/index.jsp" redirect="false" />
		<forward name="xg" path="/update.jsp" redirect="false" />
		<forward name="tolist" path="/permission.action?methodName=list" redirect="true" />
		<forward name="add" path="/add.jsp" redirect="false" />
		<forward name="ck" path="/ck.jsp" redirect="false" />
		
	
	</action>
	
	
	

</config>


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>cs02</display-name>
  <servlet>
  	<servlet-name>mvc</servlet-name>
  	<servlet-class>com.zking.framework.DispatchServlet</servlet-class>
  	<init-param>
  		<param-name>configurationLocation</param-name>
  		<param-value>/mvc.xml</param-value>
  	</init-param>
  </servlet>
  <servlet-mapping>
  	<servlet-name>mvc</servlet-name>
  	<url-pattern>*.action</url-pattern>
  </servlet-mapping>
  
 
</web-app>				

导jar包

 导写过的框架,全部导进来现在环境就搭建好了

2.基础的增删改

编写底层代码:

 实体类:

package com.xbb.entity;

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.xbb.dao;

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

import com.xbb.entity.Book;
import com.xbb.util.BaseDao;
import com.xbb.util.DBAccess;
import com.xbb.util.PageBean;
import com.xbb.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传递到后台,只传了值,没有传就是默认值,默认值就是0
		if(bid!=0) {
			sql +=" and bid ="+bid;
		}
		return super.executeQuery(sql, pageBean, rs->{
			List<Book> list = new ArrayList<Book>();
			
			try {
				while (rs.next()) {
					list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price") ));
				}
			} catch (SQLException 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 pst = con.prepareStatement(sql);
		pst.setObject(1, book.getBid());
		pst.setObject(2, book.getBname());
		pst.setObject(3, book.getPrice());
		return pst.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();
	}
	
	

}

测试类:

package com.xbb.dao;

import static org.junit.Assert.*;

import java.util.List;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

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

	@Before
	public void setUp() throws Exception{
		
	}
	@After
	public void tearDown() throws Exception{
		
	}
	
	@Test
	public void testList() {
		try {
			List<Book> list = bookDao.list(new Book(), new PageBean());
			for (Book book : list) {
				System.out.println(book);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Test
	public void testAdd()  {
		Book book = new Book(123432122, "123432122", 123432122);
		try {
			bookDao.add(book);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Test
	public void testDel() {
		Book book = new Book(123432122, "12343212255", 123432122);
		try {
			bookDao.del(book);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Test
	public void testEdit() {
		Book book = new Book(123432122, "12343212255", 123432122);
		try {
			bookDao.edit(book);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}

效果如下图:如果没有出现该效果则查询的方法有问题

 3.通用的增删改查

作用:进一步减少删改查的代码

 通用方法写到BaseDao<Book>类中

	
	//通用方法
	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(2, book.getBname());
//		pst.setObject(3, book.getPrice());
		return pst.executeUpdate();
	}
	

 根据方法不同传的参数不同

在dao方法中进行优化

package com.xbb.dao;

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

import com.xbb.entity.Book;
import com.xbb.util.BaseDao;
import com.xbb.util.DBAccess;
import com.xbb.util.PageBean;
import com.xbb.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传递到后台,只传了值,没有传就是默认值,默认值就是0
		if(bid!=0) {
			sql +=" and bid ="+bid;
		}
		return super.executeQuery(sql, pageBean, rs->{
			List<Book> list = new ArrayList<Book>();
			
			try {
				while (rs.next()) {
					list.add(new Book(rs.getInt("bid"), rs.getString("bname"), rs.getFloat("price") ));
				}
			} catch (SQLException 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 pst = con.prepareStatement(sql);
		pst.setObject(1, book.getBid());
		pst.setObject(2, book.getBname());
		pst.setObject(3, book.getPrice());
		return pst.executeUpdate();
	}*/
	
	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 {
		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 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 {
		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();
	}
	*/
	
	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"});
	}

}

然后要去测试类进行测试,如果没有错误那就成功了

4.查询删除及重复表单提交的问题及修改

package com.xbb.web;

import java.util.List;

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

import com.xbb.dao.BookDao;
import com.xbb.entity.Book;
import com.xbb.framework.ActionSupport;
import com.xbb.framework.ModelDriven;
import com.xbb.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 {
		int add = bookDao.add(book);
		//request.ex
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	//代表跳到查询界面
		return  "toList";
	}
	
//删
	public String del(HttpServletRequest request, HttpServletResponse response) {
	try {
		bookDao.add(book);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	//代表跳到查询界面
		return  "toList";
	}

	//改
	public String edit(HttpServletRequest request, HttpServletResponse response) {
		try {
			bookDao.edit(book);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//代表跳到查询界面
			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) {
				List<Book> list = bookDao.list(book, null);
				request.setAttribute("b", list.get(0));
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//代表跳到查询界面
			return  "toEdit";
		}

}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta 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>

界面:

index.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <!-- 引入c标签 -->
    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>
<center>
	<form action="${pageContext.request.contextPath }/permission.action?methodName=list"method="post">
	<a href=""></a>
	<h2>主界面</h2>
	
	<table border="1px">
	<tr>
		<td>id</td>
		<td>菜单名</td>
		<td>描述</td>
		<td>点击菜单的界面</td>
		<td>父级菜单的id</td>
		<td>菜单/按钮</td>
		<td>显示的顺序</td>
		<td>操作<a href="add.jsp">增加</a></td>
	
	</tr>
	<c:forEach items="${list }" var = "c">
	<tr>
		<td>${c.id}</td>
		<td>${c.name}</td>
		<td>${c.description}</td>
		<td>${c.url}</td>
		<td>${c.pid}</td>
		<td>${c.ismenu}</td>
		<td>${c.displayno}</td>
		<td><a href="${pageContext.request.contextPath }/permission.action?methodName=delete&id=${c.id}">删除</a></td> 
		<td><a href="${pageContext.request.contextPath }/permission.action?methodName=ck&id=${c.id}">查看</a></td>
		<td><a href="${pageContext.request.contextPath }/permission.action?methodName=tolist&id=${c.id}">修改</a></td>
	</tr>
	
	
	
	</c:forEach>
	
	
	</table>
	
	
	</form>
</center>

</body>
</html>

add.jsp:

<%@ 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>
<center>
<h2>增加界面</h2>
	<form action="${pageContext.request.contextPath }/permission.action?methodName=add" method="post">
	<table border="1px">
	<tr>
		<td>名称:</td>
		<td><input type="text" name = "name"></td>
	</tr>
	<tr>
		<td>描述:</td>
		<td><input type="text" name = "description"></td>
	</tr>
	<tr>
		<td>点击菜单的界面:</td>
		<td><input type="text" name = "url"></td>
	</tr>
	<tr>
		<td>父级菜单的id:</td>
		<td><input type="text" name = "pid"></td>
	</tr>
	<tr>
		<td>菜单/按钮:</td>
		<td><input type="text" name = "ismenu"></td>
	</tr>
	
	<tr>
		<td>显示的顺序:</td>
		<td><input type="text" name = "displayno"></td>
	</tr>
	
	
	</table>
	<input type="submit" value="提交">
	<a href="/permission.action?methodName=list">返回</a>
	
	
	
	</form>
</center>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值