• 自定义mvc框架复习


    目录

    一、搭建自定义mvc框架的环境

    导入jar包

     导入框架配套的工具类

     导入框架的配置文件

    配置web.xml

    二、完成实体类与数据库表的映射

    三、Dao层的编写

    四、web层


    哈喽大家好!!!今天就和大家一起来给自定义mvc框架进行一个收尾工作吧!!!

    一、搭建自定义mvc框架的环境

    导入jar包

     导入框架配套的工具类

    com.zking.util工具类

    BaseDao: 

    1. package com.zking.util;
    2. import java.lang.reflect.Field;
    3. import java.sql.Connection;
    4. import java.sql.PreparedStatement;
    5. import java.sql.ResultSet;
    6. import java.util.ArrayList;
    7. import java.util.List;
    8. import com.zking.entity.Book;
    9. import com.zking.util.DBAccess;
    10. import com.zking.util.PageBean;
    11. import com.zking.util.StringUtils;
    12. /**
    13. * 所有Dao层的父类
    14. * BookDao
    15. * UserDao
    16. * OrderDao
    17. * ...
    18. * @author Administrator
    19. *
    20. * @param
    21. */
    22. public class BaseDao {
    23. /**
    24. * 通用的增删改方法
    25. * @param book
    26. * @throws Exception
    27. */
    28. public void executeUpdate(String sql, T t, String[] attrs) throws Exception {
    29. // String[] attrs = new String[] {"bid", "bname", "price"};
    30. Connection con = DBAccess.getConnection();
    31. PreparedStatement pst = con.prepareStatement(sql);
    32. // pst.setObject(1, book.getBid());
    33. // pst.setObject(2, book.getBname());
    34. // pst.setObject(3, book.getPrice());
    35. /*
    36. * 思路:
    37. * 1.从传进来的t中读取属性值
    38. * 2.往预定义对象中设置了值
    39. *
    40. * t->book
    41. * f->bid
    42. */
    43. for (int i = 0; i < attrs.length; i++) {
    44. Field f = t.getClass().getDeclaredField(attrs[i]);
    45. f.setAccessible(true);
    46. pst.setObject(i+1, f.get(t));
    47. }
    48. pst.executeUpdate();
    49. }
    50. /**
    51. * 通用分页查询
    52. * @param sql
    53. * @param clz
    54. * @return
    55. * @throws Exception
    56. */
    57. public List executeQuery(String sql,Class clz,PageBean pageBean) throws Exception{
    58. List list = new ArrayList();
    59. Connection con = DBAccess.getConnection();;
    60. PreparedStatement pst = null;
    61. ResultSet rs = null;
    62. /*
    63. * 是否需要分页?
    64. * 无需分页(项目中的下拉框,查询条件教员下拉框,无须分页)
    65. * 必须分页(项目中列表类需求、订单列表、商品列表、学生列表...)
    66. */
    67. if(pageBean != null && pageBean.isPagination()) {
    68. // 必须分页(列表需求)
    69. String countSQL = getCountSQL(sql);
    70. pst = con.prepareStatement(countSQL);
    71. rs = pst.executeQuery();
    72. if(rs.next()) {
    73. pageBean.setTotal(String.valueOf(rs.getObject(1)));
    74. }
    75. // 挪动到下面,是因为最后才处理返回的结果集
    76. // -- sql=SELECT * FROM t_mvc_book WHERE bname like '%圣墟%'
    77. // -- pageSql=sql limit (page-1)*rows,rows 对应某一页的数据
    78. // -- countSql=select count(1) from (sql) t 符合条件的总记录数
    79. String pageSQL = getPageSQL(sql,pageBean);//符合条件的某一页数据
    80. pst = con.prepareStatement(pageSQL);
    81. rs = pst.executeQuery();
    82. }else {
    83. // 不分页(select需求)
    84. pst = con.prepareStatement(sql);//符合条件的所有数据
    85. rs = pst.executeQuery();
    86. }
    87. while (rs.next()) {
    88. T t = clz.newInstance();
    89. Field[] fields = clz.getDeclaredFields();
    90. for (Field f : fields) {
    91. f.setAccessible(true);
    92. f.set(t, rs.getObject(f.getName()));
    93. }
    94. list.add(t);
    95. }
    96. return list;
    97. }
    98. /**
    99. * 将原生SQL转换成符合条件的总记录数countSQL
    100. * @param sql
    101. * @return
    102. */
    103. private String getCountSQL(String sql) {
    104. // -- countSql=select count(1) from (sql) t 符合条件的总记录数
    105. return "select count(1) from ("+sql+") t";
    106. }
    107. /**
    108. * 将原生SQL转换成pageSQL
    109. * @param sql
    110. * @param pageBean
    111. * @return
    112. */
    113. private String getPageSQL(String sql,PageBean pageBean) {
    114. // (this.page - 1) * this.rows
    115. // pageSql=sql limit (page-1)*rows,rows
    116. return sql + " limit "+ pageBean.getStartIndex() +","+pageBean.getRows();
    117. }
    118. }

    PageBean.java 

    1. package com.zking.util;
    2. import java.util.HashMap;
    3. import java.util.Map;
    4. import javax.servlet.http.HttpServletRequest;
    5. /**
    6. * 分页工具类
    7. *
    8. */
    9. public class PageBean {
    10. private int page = 1;// 页码
    11. private int rows = 10;// 页大小
    12. private int total = 0;// 总记录数
    13. private boolean pagination = true;// 是否分页
    14. private String url; //保存上一次请求的URL
    15. private Map paramMap = new HashMap<>();// 保存上一次请求的参数
    16. /**
    17. * 初始化pagebean的,保存上一次请求的重要参数
    18. * @param req
    19. */
    20. public void setRequest(HttpServletRequest req) {
    21. // 1.1 需要保存上一次请求的URL
    22. this.setUrl(req.getRequestURL().toString());
    23. // 1.2 需要保存上一次请求的参数 bname、price
    24. this.setParamMap(req.getParameterMap());
    25. // 1.3 需要保存上一次请求的分页设置 pagination
    26. this.setPagination(req.getParameter("pagination"));
    27. // 1.4 需要保存上一次请求的展示条目数
    28. this.setRows(req.getParameter("rows"));
    29. // 1.5 初始化请求的页码 page
    30. this.setPage(req.getParameter("page"));
    31. }
    32. public void setPage(String page) {
    33. if(StringUtils.isNotBlank(page))
    34. this.setPage(Integer.valueOf(page));
    35. }
    36. public void setRows(String rows) {
    37. if(StringUtils.isNotBlank(rows))
    38. this.setRows(Integer.valueOf(rows));
    39. }
    40. public void setPagination(String pagination) {
    41. // 只有在前台jsp填写了pagination=false,才代表不分页
    42. if(StringUtils.isNotBlank(pagination))
    43. this.setPagination(!"false".equals(pagination));
    44. }
    45. public String getUrl() {
    46. return url;
    47. }
    48. public void setUrl(String url) {
    49. this.url = url;
    50. }
    51. public Map getParamMap() {
    52. return paramMap;
    53. }
    54. public void setParamMap(Map paramMap) {
    55. this.paramMap = paramMap;
    56. }
    57. public PageBean() {
    58. super();
    59. }
    60. public int getPage() {
    61. return page;
    62. }
    63. public void setPage(int page) {
    64. this.page = page;
    65. }
    66. public int getRows() {
    67. return rows;
    68. }
    69. public void setRows(int rows) {
    70. this.rows = rows;
    71. }
    72. public int getTotal() {
    73. return total;
    74. }
    75. public void setTotal(int total) {
    76. this.total = total;
    77. }
    78. public void setTotal(String total) {
    79. this.total = Integer.parseInt(total);
    80. }
    81. public boolean isPagination() {
    82. return pagination;
    83. }
    84. public void setPagination(boolean pagination) {
    85. this.pagination = pagination;
    86. }
    87. /**
    88. * 获得起始记录的下标
    89. *
    90. * @return
    91. */
    92. public int getStartIndex() {
    93. return (this.page - 1) * this.rows;
    94. }
    95. /**
    96. * 最大页
    97. * @return
    98. */
    99. public int maxPage() {
    100. // total % rows == 0 ? total / rows : total / rows +1
    101. return this.total % this.rows == 0 ? this.total / this.rows : this.total / this.rows + 1;
    102. }
    103. /**
    104. * 下一页
    105. * @return
    106. */
    107. public int nextPage() {
    108. // 如果当前页小于最大页,那就下一页为当前页+1;如果不小于,说明当前页就是最大页,那就无需+1
    109. return this.page < this.maxPage() ? this.page + 1 : this.page;
    110. }
    111. /**
    112. * 上一页
    113. * @return
    114. */
    115. public int previousPage() {
    116. return this.page > 1 ? this.page - 1 : this.page;
    117. }
    118. @Override
    119. public String toString() {
    120. return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
    121. }
    122. }

     导入框架的配置文件

    mvc.xml

    1. <config>
    2. <action path="/permission" type="com.zking.web.PermissionAction">
    3. <forward name="list" path="/index.jsp" redirect="false" />
    4. <forward name="xg" path="/update.jsp" redirect="false" />
    5. <forward name="tolist" path="/permission.action?methodName=list" redirect="true" />
    6. <forward name="add" path="/add.jsp" redirect="false" />
    7. <forward name="ck" path="/ck.jsp" redirect="false" />
    8. action>
    9. config>

    配置web.xml

    1. <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">
    2. <display-name>cs02display-name>
    3. <servlet>
    4. <servlet-name>mvcservlet-name>
    5. <servlet-class>com.zking.framework.DispatchServletservlet-class>
    6. <init-param>
    7. <param-name>configurationLocationparam-name>
    8. <param-value>/mvc.xmlparam-value>
    9. init-param>
    10. servlet>
    11. <servlet-mapping>
    12. <servlet-name>mvcservlet-name>
    13. <url-pattern>*.actionurl-pattern>
    14. servlet-mapping>
    15. web-app>

    二、完成实体类与数据库表的映射

    注意:数据库列段的数据类型,要与属性的类型一致
    varchar->String
    bigInt->Long
    int->int
    datetime->java.util.date

    Permission

    1. package com.zking.entity;
    2. public class Blog {
    3. private int id;
    4. private String title;
    5. private String keyWord;
    6. public int getId() {
    7. return id;
    8. }
    9. public void setId(int id) {
    10. this.id = id;
    11. }
    12. public String getTitle() {
    13. return title;
    14. }
    15. public void setTitle(String title) {
    16. this.title = title;
    17. }
    18. public String getKeyWord() {
    19. return keyWord;
    20. }
    21. public void setKeyWord(String keyWord) {
    22. this.keyWord = keyWord;
    23. }
    24. @Override
    25. public String toString() {
    26. return "Blog [id=" + id + ", title=" + title + ", keyWord=" + keyWord + "]";
    27. }
    28. }

    三、Dao层的编写

    PermissionDao

    1. package com.zking.dao;
    2. import java.util.List;
    3. import com.zking.entity.Permission;
    4. import com.zking.util.BaseDao;
    5. import com.zking.util.PageBean;
    6. /**
    7. * 继承BaseDao的原因:
    8. * 1.封装通用查询
    9. * 2.封装通用增删改
    10. * @author Administrator
    11. *
    12. */
    13. public class PermissionDao extends BaseDao{
    14. //查询
    15. public List list(Permission t, PageBean pageBean) throws Exception {
    16. String sql = "select * from t_easyui_permission where 1=1";
    17. return super.executeQuery(sql, Permission.class, pageBean);
    18. }
    19. /* //模糊查询
    20. public List mh(Permission t, PageBean pageBean) throws Exception {
    21. String sql = "select * from t_easyui_permission where ";
    22. return super.executeQuery(sql, Permission.class, pageBean);
    23. }
    24. */
    25. //查询
    26. public List dg(Permission t, PageBean pageBean) throws Exception {
    27. String sql = "select * from t_easyui_permission where 1=1";
    28. long id = t.getId();
    29. if(id!=0) {
    30. sql +=" and id="+id;
    31. }
    32. return super.executeQuery(sql, Permission.class, pageBean);
    33. }
    34. //增加
    35. public int add( Permission t) throws Exception {
    36. String sql ="insert into t_easyui_permission(name,description,url,pid,ismenu,displayno) values(?,?,?,?,?,?)";
    37. return super.executeUpdate(sql, t, new String [] {"name","description","url","pid","ismenu","displayno"} );
    38. }
    39. //修改
    40. public int update( Permission t) throws Exception {
    41. String sql ="update t_easyui_permission set name=?,description=?,url=?,pid=?,ismenu=?,displayno=? where id = ?";
    42. return super.executeUpdate(sql, t, new String [] {"name","description","url","pid","ismenu","displayno","id"} );
    43. }
    44. //删除
    45. public int delete( Permission t) throws Exception {
    46. String sql ="delete from t_easyui_permission where id = ?";
    47. return super.executeUpdate(sql, t, new String [] {"id"} );
    48. }
    49. }

    四、web层

    PermissionAction :

    1. package com.zking.web;
    2. import java.util.List;
    3. import javax.servlet.http.HttpServletRequest;
    4. import javax.servlet.http.HttpServletResponse;
    5. import com.zking.dao.PermissionDao;
    6. import com.zking.entity.Permission;
    7. import com.zking.framework.ActionSupport;
    8. import com.zking.framework.ModelDriver;
    9. import com.zking.util.PageBean;
    10. public class PermissionAction extends ActionSupport implements ModelDriver<Permission>{
    11. private Permission per = new Permission();
    12. private PermissionDao perbao = new PermissionDao();
    13. @Override
    14. public Permission getModel() {
    15. return per;
    16. }
    17. //查询
    18. public String list(HttpServletRequest req, HttpServletResponse resp) {
    19. try {
    20. //分页
    21. // PageBean pageBean = new PageBean();
    22. // //初始化
    23. // pageBean.setRequest(req);
    24. List<Permission> list = perbao.list(per, null);
    25. req.setAttribute("list", list);
    26. // req.setAttribute("pageBean", pageBean);
    27. } catch (Exception e) {
    28. e.printStackTrace();
    29. }
    30. return "list";
    31. }
    32. //增加/修改需要跳转编辑界面
    33. public String tolist(HttpServletRequest req, HttpServletResponse resp) {
    34. try {
    35. long id = per.getId();
    36. Permission p = perbao.dg(per, null).get(0);
    37. req.setAttribute("p", p);
    38. if(id!=0) {
    39. return "xg";
    40. }
    41. } catch (Exception e) {
    42. e.printStackTrace();
    43. }
    44. return "add";
    45. }
    46. public String ck(HttpServletRequest req, HttpServletResponse resp) {
    47. try {
    48. Permission p = perbao.dg(per, null).get(0);
    49. req.setAttribute("p", p);
    50. } catch (Exception e) {
    51. e.printStackTrace();
    52. }
    53. return "ck";
    54. }
    55. //增加
    56. public String add(HttpServletRequest req, HttpServletResponse resp) {
    57. try {
    58. perbao.add(per);
    59. } catch (Exception e) {
    60. e.printStackTrace();
    61. }
    62. return "tolist";
    63. }
    64. //修改
    65. public String update(HttpServletRequest req, HttpServletResponse resp) {
    66. try {
    67. perbao.update(per);
    68. } catch (Exception e) {
    69. e.printStackTrace();
    70. }
    71. return "xg";
    72. }
    73. //删除
    74. public String delete(HttpServletRequest req, HttpServletResponse resp) {
    75. try {
    76. int i = perbao.delete(per);
    77. System.out.println(i);
    78. } catch (Exception e) {
    79. e.printStackTrace();
    80. }
    81. return "tolist";
    82. }
    83. }

    五,jsp界面

    index.jsp

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    4. html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    5. <html>
    6. <head>
    7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    8. <title>Insert title heretitle>
    9. head>
    10. <h2>主界面h2>
    11. <form action="${pageContext.request.contextPath }/permission.action?methodName=list" method="post">
    12. <a href="">a>
    13. <table border="1px">
    14. <tr>
    15. <td>idtd>
    16. <td>菜单名td>
    17. <td>描述td>
    18. <td>点击菜单的界面td>
    19. <td>父级菜单的idtd>
    20. <td>菜单/按钮td>
    21. <td>显示的顺序td>
    22. <td>操作<a href="add.jsp">增加a>td>
    23. tr>
    24. <c:forEach items="${list }" var = "c">
    25. <tr>
    26. <td>${c.id}td>
    27. <td>${c.name}td>
    28. <td>${c.description}td>
    29. <td>${c.url}td>
    30. <td>${c.pid}td>
    31. <td>${c.ismenu}td>
    32. <td>${c.displayno}td>
    33. <td><a href="${pageContext.request.contextPath }/permission.action?methodName=delete&id=${c.id}">删除a>td>
    34. <td><a href="${pageContext.request.contextPath }/permission.action?methodName=ck&id=${c.id}">查看a>td>
    35. <td><a href="${pageContext.request.contextPath }/permission.action?methodName=tolist&id=${c.id}">修改a>td>
    36. tr>
    37. c:forEach>
    38. table>
    39. form>
    40. body>
    41. html>

    add.jsp

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    4. <html>
    5. <head>
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    7. <title>Insert title heretitle>
    8. head>
    9. <body>
    10. <form action="${pageContext.request.contextPath }/permission.action?methodName=add" method="post">
    11. <table border="1px">
    12. <tr>
    13. <td>名称:td>
    14. <td><input type="text" name = "name">td>
    15. tr>
    16. <tr>
    17. <td>描述:td>
    18. <td><input type="text" name = "description">td>
    19. tr>
    20. <tr>
    21. <td>点击菜单的界面:td>
    22. <td><input type="text" name = "url">td>
    23. tr>
    24. <tr>
    25. <td>父级菜单的id:td>
    26. <td><input type="text" name = "pid">td>
    27. tr>
    28. <tr>
    29. <td>菜单/按钮:td>
    30. <td><input type="text" name = "ismenu">td>
    31. tr>
    32. <tr>
    33. <td>显示的顺序:td>
    34. <td><input type="text" name = "displayno">td>
    35. tr>
    36. table>
    37. <input type="submit" value="提交">
    38. <a href="/permission.action?methodName=list">返回a>
    39. form>
    40. body>
    41. html>

    ck.jsp

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    4. <html>
    5. <head>
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    7. <title>Insert title heretitle>
    8. head>
    9. <body>
    10. <form action="${pageContext.request.contextPath }/permission.action?methodName=update" method="post">
    11. <table border="1px">
    12. <tr>
    13. <td>名称:td>
    14. <td><input type="text" name = "name" value="${p.name }">td>
    15. tr>
    16. <tr>
    17. <td>描述:td>
    18. <td><input type="text" name = "description" value="${p.description }">td>
    19. tr>
    20. <tr>
    21. <td>点击菜单的界面:td>
    22. <td><input type="text" name = "url" value="${p.url }">td>
    23. tr>
    24. <tr>
    25. <td>父级菜单的id:td>
    26. <td><input type="text" name = "pid" value="${p.pid }">td>
    27. tr>
    28. <tr>
    29. <td>菜单/按钮:td>
    30. <td><input type="text" name = "ismenu" value="${p.ismenu }">td>
    31. tr>
    32. <tr>
    33. <td>显示的顺序:td>
    34. <td><input type="text" name = "displayno" value="${p.displayno }">td>
    35. tr>
    36. table>
    37. <a href="${pageContext.request.contextPath }/permission.action?methodName=list">返回a>
    38. form>
    39. body>
    40. html>

    update.jsp

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    4. <html>
    5. <head>
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    7. <title>Insert title heretitle>
    8. head>
    9. <body>
    10. <form action="${pageContext.request.contextPath }/permission.action?methodName=update" method="post">
    11. <table border="1px">
    12. <tr>
    13. <td>名称:td>
    14. <td><input type="text" name = "name" value="${p.name }">td>
    15. tr>
    16. <tr>
    17. <td>描述:td>
    18. <td><input type="text" name = "description" value="${p.description }">td>
    19. tr>
    20. <tr>
    21. <td>点击菜单的界面:td>
    22. <td><input type="text" name = "url" value="${p.url }">td>
    23. tr>
    24. <tr>
    25. <td>父级菜单的id:td>
    26. <td><input type="text" name = "pid" value="${p.pid }">td>
    27. tr>
    28. <tr>
    29. <td>菜单/按钮:td>
    30. <td><input type="text" name = "ismenu" value="${p.ismenu }">td>
    31. tr>
    32. <tr>
    33. <td>显示的顺序:td>
    34. <td><input type="text" name = "displayno" value="${p.displayno }">td>
    35. tr>
    36. table>
    37. <input type="hidden" name="id" value="${p.id }">
    38. <input type="submit" value="提交">
    39. <a href="${pageContext.request.contextPath }/permission.action?methodName=list">返回a>
    40. form>
    41. body>
    42. html>

    运行界面:

     

  • 相关阅读:
    RK3399驱动开发 | 04 - WK2124串口芯片驱动浅析
    C/C++每日一练:实现选择排序
    蒙特卡洛树搜索(MCTS)怎么实现的?+ 上置信范围Upper Confidence Bounds(UCB)是什么?
    算法学习打卡day45|动态规划:股票问题总结
    【入门篇】ClickHouse最优秀的开源列式存储数据库
    【5】MySQL数据库备份-XtraBackup - 全量备份
    磁力链接的示例与解释
    SDK接口是什么?
    ::before 和 :after中双冒号和单冒号 有什么区别?解释一下这2个伪元素的作用
    windows查看每个程序建立的TCP链接数量
  • 原文地址:https://blog.csdn.net/weixin_63544775/article/details/126116832