自定义MVC增删改查

本文涉及的产品
云数据库 RDS SQL Server,基础系列 2核4GB
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
RDS SQL Server Serverless,2-4RCU 50GB 3个月
推荐场景:
简介: 自定义MVC增删改查

mymvcdemo是自定义mvc框架的使用示例

1.1 实体类

package com.zking.mymvc.entity;
import java.io.Serializable;
public class Book implements Serializable {
  private Integer bookid;
  private String bookname;
  private String bookname_pinyin;
  private Float price;
  private String booktype;
  public Integer getBookid() {
    return bookid;
  }
  public void setBookid(Integer bookid) {
    this.bookid = bookid;
  }
  public String getBookname() {
    return bookname;
  }
  public void setBookname(String bookname) {
    this.bookname = bookname;
  }
  public String getBookname_pinyin() {
    return bookname_pinyin;
  }
  public void setBookname_pinyin(String bookname_pinyin) {
    this.bookname_pinyin = bookname_pinyin;
  }
  public Float getPrice() {
    return price;
  }
  public void setPrice(Float price) {
    this.price = price;
  }
  public String getBooktype() {
    return booktype;
  }
  public void setBooktype(String booktype) {
    this.booktype = booktype;
  }
  public Book() {
    // TODO Auto-generated constructor stub
  }
  public Book(Integer bookid, String bookname, String bookname_pinyin, Float price, String booktype) {
    super();
    this.bookid = bookid;
    this.bookname = bookname;
    this.bookname_pinyin = bookname_pinyin;
    this.price = price;
    this.booktype = booktype;
  }
  public Book( String bookname, String bookname_pinyin, Float price, String booktype) {
    this.bookname = bookname;
    this.bookname_pinyin = bookname_pinyin;
    this.price = price;
    this.booktype = booktype;
  }
  @Override
  public String toString() {
    return "Book [bookid=" + bookid + ", bookname=" + bookname + ", bookname_pinyin=" + bookname_pinyin + ", price="
        + price + ", booktype=" + booktype + "]";
  }
}

1.2  dao方法

package com.zking.mymvc.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import com.zking.dao.BaseDao02;
import com.zking.dao.BaseDao02.ICovent;
import com.zking.mymvc.entity.Book;
import com.zking.util.DBHelper;
import com.zking.util.PageBean;
import com.zking.util.PinYinUtil;
public class BookDao implements IBookDao {
  Connection con = null;
  PreparedStatement ps = null;
  ResultSet rs = null;
  @Override
  public List<Book> getBooks(Book book, PageBean pageBean) {
    String sql="select * from tb_book where 1=1";
    List<Object> ls = new ArrayList<>();
    if(book != null && book.getBookname() !=null && !"".equals(book.getBookname())) {
      sql +=" and bookname like ?";
      ls.add("%"+book.getBookname()+"%") ;
    }
     return BaseDao02.query(sql, ls.toArray(), pageBean, new ICovent<Book>() {
      @Override
      public List<Book> convent(ResultSet rs) throws SQLException {
        List<Book> list = new ArrayList<>();
        while(rs.next()) {
          Book book = new Book();
          book.setBookid(rs.getInt("bookid"));
          book.setBookname(rs.getString("bookname"));
          book.setBookname_pinyin(rs.getString("bookname_pinyin"));
          book.setPrice(rs.getFloat("price"));
          book.setBooktype(rs.getString("booktype"));
          list.add(book);
        }
        return list;
      }
    });
  }
  @Override
  public void addBook(Book book) {
    System.out.println(book);
    try {
      //创建连接
      con=DBHelper.getConnection();
      //SQL语句
      String sql="insert into tb_book(bookname,bookname_pinyin,price,booktype) values(?,?,?,?)";
      //执行语句
      ps=con.prepareStatement(sql);
      //赋值ֵ
      ps.setString(1,book.getBookname());
      ps.setString(2,PinYinUtil.toPinyin(book.getBookname().toLowerCase()));
      ps.setFloat(3, book.getPrice());
      ps.setString(4, book.getBooktype());
      ps.executeUpdate();
    } catch (Exception e) {
      e.printStackTrace();
    }finally {
      DBHelper.close(con, ps, null);
    }
  }
  @Override
  public int deleteBook(int bookid) {
    int n = 0;
    try {
      //创建连接
      con=DBHelper.getConnection();
      //定义SQL语句
      String sql="delete from tb_book where bookid=?";
      //获得执行语句
      ps=con.prepareStatement(sql);
      //赋值
      ps.setInt(1, bookid);
      n=ps.executeUpdate();
    } catch (Exception e) {
      e.printStackTrace();
    }finally {
      DBHelper.close(con, ps, rs);
    }
    return n;
  }
  @Test
  public void testGetBook() {
    Book book = new Book();
    book.setBookname("西");
    PageBean pageBean = new PageBean();
    pageBean.setRows(5);
    pageBean.setPage(2);
    List<Book> list = getBooks(book, pageBean);
    list.forEach(System.out::println);
  }
  @Test
  public void testAddBook() {
    Book book = new Book("哈哈哈", "hhh", 34.33f, "小说");
    BookDao bd = new BookDao();
    bd.addBook(book);
  }
}
package com.zking.mymvc.dao;
import java.util.List;
import com.zking.mymvc.entity.Book;
import com.zking.util.PageBean;
public interface IBookDao {
  /**
   * 查询方法
   * @param book
   * @param pageBean
   * @return
   */
  List<Book> getBooks(Book book, PageBean pageBean);
  /**
   * 增加方法
   * @param book
   */
  void addBook(Book book);
  /**
   * 删除方法
   * @param bookid
   * @return
   */
  int deleteBook(int bookid);
}

1.3 写Service / biz 三层架构

package com.zking.mymvc.service;
import java.util.List;
import com.zking.mymvc.dao.BookDao;
import com.zking.mymvc.dao.IBookDao;
import com.zking.mymvc.entity.Book;
import com.zking.util.PageBean;
/**
 * @author PC
 *
 */
public class BookService implements IBookService {
  private IBookDao dao = new BookDao();
  @Override
  public List<Book> getBooks(Book book,PageBean pageBean) {
    return dao.getBooks(book, pageBean);
  }
  @Override
  public void addBook(Book book) {
    dao.addBook(book);
  }
  @Override
  public void deleteBook(int bookid) {
    dao.deleteBook(bookid);
  }
}
package com.zking.mymvc.service;
import java.util.List;
import com.zking.mymvc.entity.Book;
import com.zking.util.PageBean;
public interface IBookService {
  List<Book> getBooks(Book book,PageBean pageBean);
  void addBook(Book book);
  void deleteBook(int bookid);
}

1.4 建action 相当于selvert

package com.zking.mymvc.action;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zking.framework.AbstractDispatchAction;
import com.zking.framework.ModelDrive;
import com.zking.mymvc.entity.Book;
import com.zking.mymvc.service.BookService;
import com.zking.mymvc.service.IBookService;
import com.zking.util.PageBean;
public class BookAction extends AbstractDispatchAction implements ModelDrive {
  private Book book = new Book();
  @Override
  public Object getModel() {
    return book;
  }
  //查询
  private IBookService service = new BookService();
  public String getBooks(HttpServletRequest req,HttpServletResponse resp) {
    PageBean pageBean = new PageBean();
    pageBean.setRequest(req);
    pageBean.setRows(5);
    List<Book> bookPager = service.getBooks(book, pageBean);
    req.setAttribute("bookPager", bookPager);
    return "book";
  }
  /**
   * 增加
   * @param req
   * @param resp
   * @return
   */
  public String addBook(HttpServletRequest req,HttpServletResponse resp) {
    service.addBook(book);
    return "success";
  }
  /**
   * 删除
   * @param req
   * @param resp
   * @return
   */
  public String deleteBook(HttpServletRequest req,HttpServletResponse resp) {
    service.deleteBook(book.getBookid());
    return "ok";
  }
}

1.5 con连接MySQL 8.0 版本

#oracle9i
#driver=oracle.jdbc.driver.OracleDriver
#url=jdbc:oracle:thin:@localhost:1521:orcl
#user=scott
#pwd=123
#sql2005
#driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
#url=jdbc:sqlserver://localhost:1433;DatabaseName=test1
#user=sa
#pwd=123
#sql2000
#driver=com.microsoft.jdbc.sqlserver.SQLServerDriver
#url=jdbc:microsoft:sqlserver://localhost:1433;databaseName=unit6DB
#user=sa
#pwd=888888
#mysql
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/tb_books?useUnicode=true&characterEncoding=UTF-8&useSSL=false&allowPublicKeyRetrieval=true
#url=jdbc:mysql://119.23.46.143:3306/db_s2_easyui?useUnicode=true&characterEncoding=UTF-8&useSSL=false
user=root
pwd=123456

1.6 配置文件 XML

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE config[
  <!ELEMENT config (action*)>
  <!ELEMENT action (forward*)>
  <!ELEMENT forward EMPTY>
  <!ATTLIST action
    path CDATA #REQUIRED
    type CDATA #REQUIRED
  >
  <!ATTLIST forward
    name CDATA #REQUIRED
    path CDATA #REQUIRED
    redirect (true|false) "false"
  >
]>
<config>
  <action path="/bookAction" type="com.zking.mymvc.action.BookAction">
    <forward name="book" path="/bookList.jsp" redirect="false"/>
    <forward name="success" path="http://localhost:8080/J2EE_mymvcdemo/bookAction.action?methodName=getBooks" redirect="true"/>
    <forward name="ok" path="http://localhost:8080/J2EE_mymvcdemo/bookAction.action?methodName=getBooks" redirect="true"/>
  </action>
</config>

1.7 主界面布局

<%@page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="z" uri="/zking"%>
<!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>通用分页案例书本信息</title>
</head>
<body>
  <h1>书本信息</h1>
  <form action="<%=request.getContextPath()%>/bookAction.action?methodName=getBooks" method="post">
    <input type="text" name="bookname" value="<%=request.getParameter("bookname")==null ? "" : request.getParameter("bookname")%>"/> 
    <input type="submit" value="查询">
  </form>
  <table width="100%" border="1" cellpadding="0" cellspacing="0">
    <thead>
      <tr>
      <td>书本编号</td>
      <td>书本名字</td>
      <td>书本拼音</td>
      <td>书本价格</td>
      <td>书本类型</td>
      <td>操作<a href="<%=request.getContextPath()%>/addBook.jsp">增加</a></td>
    </tr>
    </thead>
      <c:forEach items="${bookPager}" var="b">
      <tr>
        <td>${b.bookid}</td>
        <td>${b.bookname}</td>
        <td>${b.bookname_pinyin}</td>
        <td>${b.price}</td>
        <td>${b.booktype}</td>
        <td><a href="<%=request.getContextPath()%>/bookAction.action?methodName=deleteBook&bookid=${b.bookid}">删除</a></td>
      </tr>
    </c:forEach>
  </table>
  <z:paging pageBean="${pageBean}"/>
</body>
</html>

1.8 增加界面布局

<%@ 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>
  <h1>增加</h1>
  <form action="<%=request.getContextPath()%>/bookAction.action?methodName=addBook" method="post">
    书本名字: <input type="text" name="bookname"><br>
    书本价格: <input type="text" name="price"><br>
    书本类型: <input type="text" name="booktype"><br>
    <input type="submit" value="提交">
  </form>
</body>
</html>

1.9 写tld配置文件

<!DOCTYPE taglib
  PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
   "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<!-- 标签库描述符 -->
<taglib xmlns="http://java.sun.com/JSP/TagLibraryDescriptor">
  <tlib-version>1.0</tlib-version>
  <jsp-version>1.2</jsp-version>
  <short-name>Simple Tags</short-name>
  <uri>/zking</uri>
  <tag>
    <name>paging</name>
    <tag-class>com.zking.tag.PagingTag</tag-class>
    <body-content>empty</body-content>
    <attribute>
      <name>pageBean</name>
      <required>true</required>
      <rtexprvalue>true</rtexprvalue>
    </attribute>
  </tag>
  </taglib>

2.0 注意架包 我是已经打包好的

 


相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
1月前
|
前端开发 Java 数据库
springBoot:template engine&自定义一个mvc&后端给前端传数据&增删改查 (三)
本文介绍了如何自定义一个 MVC 框架,包括后端向前端传递数据、前后端代理配置、实现增删改查功能以及分页查询。详细展示了代码示例,从配置文件到控制器、服务层和数据访问层的实现,帮助开发者快速理解和应用。
|
6月前
|
前端开发 Java 网络安全
ssh(Spring+Spring mvc+hibernate)简单增删改查案例
ssh(Spring+Spring mvc+hibernate)简单增删改查案例
|
6月前
|
前端开发 Java
自定义mvc的增删改查
自定义mvc的增删改查
63 0
|
6月前
|
XML 前端开发 数据格式
自定义MVC引用XML配置文件实现
自定义MVC引用XML配置文件实现
63 0
|
6月前
|
设计模式 前端开发 搜索推荐
自定义mvc框架
自定义mvc框架
67 0
|
11月前
|
设计模式 前端开发
自定义mvc
自定义mvc
50 0
|
11月前
|
前端开发 Java 程序员
Spring-MVC的crud增删改查--详细讲解
Spring-MVC的crud增删改查--详细讲解
|
11月前
|
XML 前端开发 数据格式
自定义MVC超详细易懂----增删改查
自定义MVC超详细易懂----增删改查
102 0
|
3月前
|
开发框架 前端开发 .NET
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
47 0
|
6月前
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
191 0