当前位置:网站首页>Custom mvc framework review
Custom mvc framework review
2022-08-02 12:32:00 【Price pit pit】
目录
Import the tool classes that come with the framework
Import the framework's configuration file
二、Complete the mapping of entity classes and database tables
哈喽大家好!!!Come and customize with you todaymvcLet's put the finishing touches on the framework!!!
一、搭建自定义mvc框架的环境
导入jar包
Import the tool classes that come with the framework
com.zking.util工具类
BaseDao:
package com.zking.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.zking.entity.Book;
import com.zking.util.DBAccess;
import com.zking.util.PageBean;
import com.zking.util.StringUtils;
/**
* 所有Dao层的父类
* BookDao
* UserDao
* OrderDao
* ...
* @author Administrator
*
* @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", "price"};
Connection con = DBAccess.getConnection();
PreparedStatement pst = con.prepareStatement(sql);
// pst.setObject(1, book.getBid());
// pst.setObject(2, book.getBname());
// pst.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);
pst.setObject(i+1, f.get(t));
}
pst.executeUpdate();
}
/**
* 通用分页查询
* @param sql
* @param clz
* @return
* @throws Exception
*/
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 = 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();
}
}
PageBean.java
package com.zking.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<String,String[]> 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<String, String[]> getParamMap() {
return paramMap;
}
public void setParamMap(Map<String, String[]> 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 + "]";
}
}
Import the framework's configuration file
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>
二、Complete the mapping of entity classes and database tables
注意:The data type of the database column segment,To be consistent with the type of the property
varchar->String
bigInt->Long
int->int
datetime->java.util.date
Permission
package com.zking.entity;
public class Blog {
private int id;
private String title;
private String keyWord;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getKeyWord() {
return keyWord;
}
public void setKeyWord(String keyWord) {
this.keyWord = keyWord;
}
@Override
public String toString() {
return "Blog [id=" + id + ", title=" + title + ", keyWord=" + keyWord + "]";
}
}
三、Dao层的编写
PermissionDao
package com.zking.dao;
import java.util.List;
import com.zking.entity.Permission;
import com.zking.util.BaseDao;
import com.zking.util.PageBean;
/**
* 继承BaseDao的原因:
* 1.封装通用查询
* 2.封装通用增删改
* @author Administrator
*
*/
public class PermissionDao extends BaseDao<Permission>{
//查询
public List<Permission> list(Permission t, PageBean pageBean) throws Exception {
String sql = "select * from t_easyui_permission where 1=1";
return super.executeQuery(sql, Permission.class, pageBean);
}
/* //模糊查询
public List<Permission> mh(Permission t, PageBean pageBean) throws Exception {
String sql = "select * from t_easyui_permission where ";
return super.executeQuery(sql, Permission.class, pageBean);
}
*/
//查询
public List<Permission> dg(Permission t, PageBean pageBean) throws Exception {
String sql = "select * from t_easyui_permission where 1=1";
long id = t.getId();
if(id!=0) {
sql +=" and id="+id;
}
return super.executeQuery(sql, Permission.class, pageBean);
}
//增加
public int add( Permission t) throws Exception {
String sql ="insert into t_easyui_permission(name,description,url,pid,ismenu,displayno) values(?,?,?,?,?,?)";
return super.executeUpdate(sql, t, new String [] {"name","description","url","pid","ismenu","displayno"} );
}
//修改
public int update( Permission t) throws Exception {
String sql ="update t_easyui_permission set name=?,description=?,url=?,pid=?,ismenu=?,displayno=? where id = ?";
return super.executeUpdate(sql, t, new String [] {"name","description","url","pid","ismenu","displayno","id"} );
}
//删除
public int delete( Permission t) throws Exception {
String sql ="delete from t_easyui_permission where id = ?";
return super.executeUpdate(sql, t, new String [] {"id"} );
}
}
四、web层
PermissionAction :
package com.zking.web;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zking.dao.PermissionDao;
import com.zking.entity.Permission;
import com.zking.framework.ActionSupport;
import com.zking.framework.ModelDriver;
import com.zking.util.PageBean;
public class PermissionAction extends ActionSupport implements ModelDriver<Permission>{
private Permission per = new Permission();
private PermissionDao perbao = new PermissionDao();
@Override
public Permission getModel() {
return per;
}
//查询
public String list(HttpServletRequest req, HttpServletResponse resp) {
try {
//分页
// PageBean pageBean = new PageBean();
// //初始化
// pageBean.setRequest(req);
List<Permission> list = perbao.list(per, null);
req.setAttribute("list", list);
// req.setAttribute("pageBean", pageBean);
} catch (Exception e) {
e.printStackTrace();
}
return "list";
}
//增加/Modifications require jumping to the editing interface
public String tolist(HttpServletRequest req, HttpServletResponse resp) {
try {
long id = per.getId();
Permission p = perbao.dg(per, null).get(0);
req.setAttribute("p", p);
if(id!=0) {
return "xg";
}
} catch (Exception e) {
e.printStackTrace();
}
return "add";
}
public String ck(HttpServletRequest req, HttpServletResponse resp) {
try {
Permission p = perbao.dg(per, null).get(0);
req.setAttribute("p", p);
} catch (Exception e) {
e.printStackTrace();
}
return "ck";
}
//增加
public String add(HttpServletRequest req, HttpServletResponse resp) {
try {
perbao.add(per);
} catch (Exception e) {
e.printStackTrace();
}
return "tolist";
}
//修改
public String update(HttpServletRequest req, HttpServletResponse resp) {
try {
perbao.update(per);
} catch (Exception e) {
e.printStackTrace();
}
return "xg";
}
//删除
public String delete(HttpServletRequest req, HttpServletResponse resp) {
try {
int i = perbao.delete(per);
System.out.println(i);
} catch (Exception e) {
e.printStackTrace();
}
return "tolist";
}
}
五,jsp界面
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>
<h2>主界面</h2>
<form action="${pageContext.request.contextPath }/permission.action?methodName=list" method="post">
<a href=""></a>
<table border="1px">
<tr>
<td>id</td>
<td>菜单名</td>
<td>描述</td>
<td>Click the menu interface</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>
</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>
<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>Click the menu interface:</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>
</body>
</html>
ck.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>
<form action="${pageContext.request.contextPath }/permission.action?methodName=update" method="post">
<table border="1px">
<tr>
<td>名称:</td>
<td><input type="text" name = "name" value="${p.name }"></td>
</tr>
<tr>
<td>描述:</td>
<td><input type="text" name = "description" value="${p.description }"></td>
</tr>
<tr>
<td>Click the menu interface:</td>
<td><input type="text" name = "url" value="${p.url }"></td>
</tr>
<tr>
<td>父级菜单的id:</td>
<td><input type="text" name = "pid" value="${p.pid }"></td>
</tr>
<tr>
<td>菜单/按钮:</td>
<td><input type="text" name = "ismenu" value="${p.ismenu }"></td>
</tr>
<tr>
<td>显示的顺序:</td>
<td><input type="text" name = "displayno" value="${p.displayno }"></td>
</tr>
</table>
<a href="${pageContext.request.contextPath }/permission.action?methodName=list">返回</a>
</form>
</body>
</html>
update.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>
<form action="${pageContext.request.contextPath }/permission.action?methodName=update" method="post">
<table border="1px">
<tr>
<td>名称:</td>
<td><input type="text" name = "name" value="${p.name }"></td>
</tr>
<tr>
<td>描述:</td>
<td><input type="text" name = "description" value="${p.description }"></td>
</tr>
<tr>
<td>Click the menu interface:</td>
<td><input type="text" name = "url" value="${p.url }"></td>
</tr>
<tr>
<td>父级菜单的id:</td>
<td><input type="text" name = "pid" value="${p.pid }"></td>
</tr>
<tr>
<td>菜单/按钮:</td>
<td><input type="text" name = "ismenu" value="${p.ismenu }"></td>
</tr>
<tr>
<td>显示的顺序:</td>
<td><input type="text" name = "displayno" value="${p.displayno }"></td>
</tr>
</table>
<input type="hidden" name="id" value="${p.id }">
<input type="submit" value="提交">
<a href="${pageContext.request.contextPath }/permission.action?methodName=list">返回</a>
</form>
</body>
</html>
运行界面:
边栏推荐
- 一款强大的js弹出alert插件
- LeetCode_139_单词拆分
- kvm部署
- How to set up wireless PPI communication between Weiluntong touch screen and S7-200smart?
- np.nan, np.isnan, None, pd.isnull, pd.isna 整理与小结
- Distributed current limiting, hand & redisson implementation
- php——三篇夯实根基第一篇
- Likou 977-Squaring of ordered arrays - brute force method & double pointer method
- Speed up your programs with bitwise operations
- Likou 704 - binary search
猜你喜欢
数据湖(一):数据湖概念
Basic protocol explanation
力扣704-二分查找
干测试这些年,去过阿里也去过小公司,给年轻测试员们一个忠告...
分布式限流利器,手撕&redisson实现
Seneor曝光基础知识
How to set up wireless PPI communication between Weiluntong touch screen and S7-200smart?
Likou 704 - binary search
Speed up your programs with bitwise operations
The 7 most commonly used data analysis thinking, solve 95% of the analysis problems
随机推荐
第11章 文件
Process finished with exit code 1
数据湖(三):Hudi概念术语
PHP+MYSQL【学生信息管理系统】(极简版)
FreeRTOS experiment -- delete task
基础协议讲解
Pod Scheduling Strategy: Affinity, Stain and Stain Tolerance
7种最常用数据分析思维,解决95%的分析难题
Taurus.MVC V3.0.3 微服务开源框架发布:让.NET 架构在大并发的演进过程更简单。
Openlayers 快速上手教程
服务器间传输文件
Likou 35 - search for insertion position - binary search
翻译英语的软件-免费翻译软件-各种语言互相翻译
photo-sphere-viewer中文文档
力扣704-二分查找
The ex-boyfriend bought chili water and threatened to rob his daughter. Can the woman apply for a personal safety protection order?
图神经网络(GNN)的简介「建议收藏」
自己如何做小程序呢?
DTG-SSOD: The latest semi-supervised detection framework, Dense Teacher (with paper download)
pig4cloud服务架构使用