项目结构:本项目有部分取置于以前的代码(需要的可前往主页查看)
一,导入jar包 根据如下操作把上节课我们写的自定义框架导成jar包(自定义框架在我CSDN主页)
导入自定义MVC框架所使用的相关jar包
二,做配置 (WEB-INF 下的 web.xml 文件)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>xxx</display-name>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>com.lgs.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>
根目录下 mvc.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/book" type="com.lgs.web.BookAction">
<forward name="list" path="/bookList.jsp" redirect="false" />
<forward name="toList" path="/book.action?methodName=list" redirect="true" />
<forward name="toEdit" path="/bookEdit.jsp" redirect="false" />
</action>
</config>
三,开发
Book实体类
package com.zking.ydz.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(int bid, String bname, float price) {
super();
this.bid = bid;
this.bname = bname;
this.price = price;
}
public Book() {
// TODO Auto-generated constructor stub
}
}
dao方法(BookDao继承BaseDao<T>)
package com.zking.ydz.dao;
import java.util.List;
import com.lgs.entity.Book;
import com.lgs.util.BaseDao;
import com.lgs.util.PageBean;
import com.lgs.util.StringUtils;
public class BookDao extends BaseDao<Book>{
/*
* 增删改查套路
* 1,建立连接
* 2,预定义对象prepareStatement
* 3,设置占位符
* 4,pst.executeUpdate();
*/
public void add(Book book) throws Exception {
String sql = "insert into t_mvc_book values(?,?,?)";
super.executeUpdate(sql,book,new String[] {"bid","bname","price"});
}
public void delete(Book book) throws Exception {
String sql = "delete from t_mvc_book where bid = ? ";
super.executeUpdate(sql,book,new String[] {"bid"});
}
public void edit(Book book) throws Exception {
String sql = "update t_mvc_book set bname = ? , price = ? where bid = ?";
super.executeUpdate(sql,book,new String[] {"bname","price","bid"});
}
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+"%'";
}
return super.executeQuery(sql, Book.class, pageBean);
}
BaseDao<T>(通用父类)
package com.lgs.util;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import com.lgs.entity.Book;
import com.lgs.util.DBAccess;
import com.lgs.util.PageBean;
import com.lgs.util.StringUtils;
/**
解决方法:
1,抽取变化部分作为参数(sql,class对象)
2,抽取公共的父类,把重复代码剥离出来
*/
public class BaseDao<T> {
// 通用的增删改方法
public void executeUpdate(String sql,T t,String[] attrs) throws Exception {
// String[] attrs = new String[] {"bid","bname","price"};
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
// 思路:1,从传进来的t中读取属性值 2,往预定义对象中设置值(用反射)
// pst.setObject(1, book.getBid()); pst.setObject(2, book.getBname()); pst.setObject(3, book.getPrice());
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.executeUpdate();
}
// 通用分页查询
public List<T> executeQuery(String sql,Class<T> clz,PageBean pageBean) throws Exception{
List<T> list=new ArrayList<T>();
Connection con = DBAccess.getConnection();
PreparedStatement pst = null;
ResultSet rs = null;
/*
* 是否需要分页?
* 无需分页(项目中的下拉框)
* 必须分页(列表需求)
*/
if(pageBean != null && pageBean.isPagination()) {
// 必须分页(列表需求)
String countSQL = getPagesSQL(sql);
pst = con.prepareStatement(countSQL);//符合条件的某一页数据
rs = pst.executeQuery();
if(rs.next()) {
pageBean.setTotal(String.valueOf(rs.getObject(1)));
}
String pageSQL = getPagesSQL(sql,pageBean);
pst = con.prepareStatement(pageSQL);//符合条件的某一页数据
rs = pst.executeQuery();
}else {
// 无需分页(项目中的下拉框)
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
*/
private String getPagesSQL(String sql) {
return "select count(1) from ("+sql+") t";
}
/*
* 将原生SQL转换成pageSQL
*/
private String getPagesSQL(String sql,PageBean pageBean) {
return sql +" limit "+ pageBean.getStartIndex()+","+pageBean.getRows();
}
}
子控制层(BookAction)
目标:利用郑江做的自定义mvc框架完成增删改查 通用的分页查询 通用的增删改
步骤:
1,导入框架的jar包
2,做好框架的使用配置
3,一切照旧(jsp,servlet/BookAction,Dao层,entity)
注意:
增删改最终都要跳回查询界面
分析:增删改查一共有多少结果集的配置
查询:BookList.jsp 返回值:list
增删改(点击取消):Book.action?methodName=list 返回值:toList
增加修改跳转对应界面:BookEdir.jsp 返回值:toEdit
子控制器
*目标:利用郑江做的自定义mvc框架完成增删改查 通用的分页查询 通用的增删改
步骤:
* 1,导入框架的jar包
* 2,做好框架的使用配置
* 3,一切照旧(jsp,servlet/BookAction,Dao层,entity)
*
*/
增删改最终都要跳回查询界面
分析:增删改查一共有多少结果集的配置
查询:BookList.jsp 返回值:list
增删改(点击取消):Book.action?methodName=list 返回值:toList
增加修改跳转对应界面:BookEdir.jsp 返回值:toEdit
jsp界面(bookList首页)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp/jstl/core" 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="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>
<body>
<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="请输入书籍名称">
<!-- <input name="rows" value="20" type="hidden"> 一页显示二十行-->
<!-- <input name="pagination" value="false" type="hidden"> 不分页-->
</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=toEdit">新增</a>
</form>
<table class="table table-striped bg-success">
<thead>
<tr>
<th scope="col">书籍ID</th>
<th scope="col">书籍名</th>
<th scope="col">价格</th>
<th scope="col">操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="b" items="${books }">
<tr>
<td>${b.bid }</td>
<td>${b.bname }</td>
<td>${b.price }</td>
<td>
<a href="${pageContext.request.contextPath }/book.action?methodName=toEdit&bid=${b.bid}">修改</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=delete&bid=${b.bid}">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<z:page pageBean="${pageBean }"></z:page>
</body>
</html>