目录
思维导图
一.优化配置文件
二.?导jar包
?三.做配置
?四.开发
五.页面展示
思维导图
一.优化配置文件
1.新建一个source folder文件夹
将framework下的config.xml复制到conf文件夹下
?
2.在中央控制器中的、将@WebServlet("*.action")注掉
3.?在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">
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>com.ysq.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>
4.中央控制器中
public void init() throws ServletException {
try {
String configurationLocation=this.getInitParameter("configurationLocation");
//web.xml中有配置configurationLocation
if(StringUtils.isNotBlank(configurationLocation)) {
configModel=ConfigModelFactory.build(configurationLocation);
}else {
//web.xml中没有配置configurationLocation 默认的
configModel=ConfigModelFactory.build();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
二.?导jar包
1.把自定义MVC框架导成一个jar包
利用之前自定义的MVC的framework类和通用分页中的tag类、util类打成一个jar包,右键-->Export-->选择JAR file->选择路径->导出mvc.jar包
?导入项目所需jar包
?三.做配置
?1..WEB-INF 下的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_mvc</display-name>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>com.ysq.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>
?2.根路径下 mvc.xml
?
<?xml version="1.0" encoding="UTF-8"?>
<config>
<!-- 在这里每加一个配置,就相当于写了 actions.put("/goods",new GoodsAction());这样就解决了代码灵活性问题 false代表转发-->
<action path="/book" type="com.ysq.web.BookAction">
<!-- 查询:bookList.jsp 返回值:list -->
<!-- 增删改点确定的是:book.action?methodName=list 返回值:toList -->
<!-- 增加修改跳转对应界面:bookEdit.jsp 返回值:toEdit -->
<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>
?四.开发
1.实体类
package com.ysq.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;
}
@Override
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + ", 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
}
}
2.Dao方法(要继承BaseDao)
com.ysq.util中BaseDao在打包前增加通用增删改方法
BaseDao:
package com.ysq.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.ysq.entity.Book;
import com.ysq.util.DBAccess;
import com.ysq.util.PageBean;
/**
* 所有Dao层的父类
* @author T440s
*
* @param <T>
*/
public class BaseDao<T> {
/**
* 通用的增删改方法
* @param book
* @throws Exception
*/
public void executeUpdate(String sql,T t,String[] attrs) throws Exception {
// String[] attrs=new String[] {"bid","bname","pricae"}
Connection con= DBAccess.getConnection();
PreparedStatement ps=con.prepareStatement(sql);
// ps.setObject(1, book.getBid());
// ps.setObject(2, book.getBname());
// ps.setObject(3, book.getPrice());
/**
* 思路
* 1.从传进来的的t中读取属性值
* 2.往预定义对象中设置了值
* t->book
* f->bid
*/
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));
}
ps.executeUpdate();
}
/**
* 通用分页查询
* @param sql
* @param clz
* @return
* @throws Exception
*/
public List<T> executeQuery(String sql,Class<T> clz, PageBean pageBean)throws Exception{
//不确定list集合中装的什么东西 子类Dao继承BaseDao<T>,子类传的是什么类那么list集合中放的就是什么
List<T> list=new ArrayList<T>();
Connection con = DBAccess.getConnection();
PreparedStatement ps = null;
ResultSet rs=null;
/*
* 是否需要分页?
* 无序分页(项目中的下拉框,查询条件教员下拉框 无需分页)
* 必须分页(项目中列表类需求、订单列表、商品列表、学生列表。。。)
*/
if(pageBean !=null&&pageBean.isPagination()) {
// 必须分页
String countSQL=getCountSQL(sql);
ps = con.prepareStatement(countSQL);
rs=ps.executeQuery();
if(rs.next()) {
pageBean.setTotal(String.valueOf(rs.getObject(1)));
}
// -- sql = select * from t_mvc_book where bname like '%圣墟%'
// -- pageSql= sql limit (n-1)*rows,rows //对应某一页的数据
// -- countSql=select count(1) from (sql) t //符合条件的总记录数
String pageSQL=getPageSQL(sql,pageBean);//符合条件的某一页数据
ps = con.prepareStatement(pageSQL);
rs = ps.executeQuery();
}else {
// 不分页
con = DBAccess.getConnection();
ps = con.prepareStatement(sql);//符合条件的所有数据
rs=ps.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();
}
}
package com.ysq.dao;
import java.util.List;
import com.ysq.entity.Book;
import com.ysq.util.BaseDao;
import com.ysq.util.PageBean;
import com.ysq.util.StringUtils;
public class BookDao extends BaseDao<Book> {
/*原来的
* public void add(Book book) throws Exception {
String sql="insert into t_mvc_book values(?,?,?)";
Connection con= DBAccess.getConnection();
PreparedStatement ps=con.prepareStatement(sql);
ps.setObject(1, book.getBid());
ps.setObject(2, book.getBname());
ps.setObject(3, book.getPrice());
ps.executeUpdate();
增删改查的通用套路
1、建立连接
2、预定义对象PreparedStatement
3、设置占位符?的值
4、ps.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();
int bid = book.getBid();
if(bid !=0) {
sql += "and bid ="+bid;
}
if(StringUtils.isNotBlank(bname)) {
sql += " and bname like '%"+bname+"%'";
}
return super.executeQuery(sql, Book.class, pageBean);
}
}
3、子控制器(继承ActionSupport实现ModelDriver<T>)
package com.ysq.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ysq.dao.BookDao;
import com.ysq.entity.Book;
import com.ysq.framework.ActionSupport;
import com.ysq.framework.ModelDriver;
import com.ysq.util.PageBean;
/**
* 目标:
* 利用自己做的自定义MVC框架完成增删改查
* 通用的分页查询
* 通用的增删改查
* 步骤
* 1、导入框架的jar包
* 2、做好框架的使用配置
* 3、一切照旧
* jsp、servlt/BookAction、Dao层、entity
*
* @author zjjt
*
*/
public class BookAction extends ActionSupport implements ModelDriver<Book>{
private Book book=new Book();
private BookDao bookDao=new BookDao();
@Override
public Book getModel() {
return book;
}
/**
* 增删改最终都要跳回查询页面
* 增删改查一共有多少结果集的配置
* 查询:bookList.jsp 返回值:list
* 增删改点确定的是:book.action?methodName=list 返回值:toList
* 增加修改跳转对应界面:bookEdit.jsp 返回值:toEdit
*/
public String add(HttpServletRequest req, HttpServletResponse resp) {
try {
bookDao.add(book);
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
public String delete(HttpServletRequest req, HttpServletResponse resp) {
try {
bookDao.delete(book);
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
public String edit(HttpServletRequest req, HttpServletResponse resp) {
try {
bookDao.edit(book);
} catch (Exception e) {
e.printStackTrace();
}
return "toList";
}
public String list(HttpServletRequest req, HttpServletResponse resp) {
try {
PageBean pageBean=new PageBean();
pageBean.setRequest(req);
List<Book> list = bookDao.list(book, pageBean);
req.setAttribute("books",list );
req.setAttribute("pageBean", pageBean);
bookDao.edit(book);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "list";
}
/**
* 跳转到新增修改界面
* @param req
* @param resp
* @return
*/
public String toEdit(HttpServletRequest req, HttpServletResponse resp) {
try {
/*
* 如果是跳转修改页面,那么需要做bid条件的精准查询
*/
if(book.getBid() != 0) {
List<Book> list = bookDao.list(book, null);
req.setAttribute("b", list.get(0));
}
} catch (Exception e) {
e.printStackTrace();
}
return "toEdit";
}
}
4、页面
①、展示页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://jsp.veryedu.cn" prefix="y"%>
<%@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="请输入书籍名称">
</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>
<y:page pageBean="${pageBean }"></y:page>
</body>
</html>
②增加修改页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://jsp.veryedu.cn" prefix="y"%>
<%@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>
</head>
<body>
<form class="form-inline"
action="${pageContext.request.contextPath }/book.action?methodName=${empty b ? 'add' : 'edit'}" method="post">
书籍id:<input type="text" name="bid" value="${b.bid }"><br>
书籍名称:<input type="text" name="bname" value="${b.bname }"><br>
书籍价格:<input type="text" name="price" value="${b.price }"><br>
<input type="submit">
</form>
</body>
</html>
五.页面展示
查询
?增加
?修改
?
?
|