前言
最近写了个课设,刚好刚学完javaweb需要巩固一下,课设内容是java增删改查,想睡觉有人送枕头了属于是,这里我是实现了增删改查,删除那里我就偷懒了,只写了批量删除。(实际上就是黑马项目套皮,不过我实现了修改功能,还是有点价值滴)
项目逻辑
后端写好Servlet服务,前端通过ajax申请服务,并将表中数据通过Servlet与后台数据库交互,从而达到前端和后端互通的效果。
一、Mapper层实现代码
1.BookMapper.class
代码如下(示例):
package com.MyJavaClass.mapper;import com.MyJavaClass.pojo.Book;import org.apache.ibatis.annotations.*;import java.util.List;public interface BookMapper { @Select("select * from books") List<Book> selectAll(); @Insert("insert into books values(null,#{bookName},#{writer},#{user},#{number},#{state})") void add(Book book); List<Book> selectBycondition(); void deleteByIds(@Param("ids")int[] ids); @Select("select * from books limit #{begin}, #{size}") List<Book> selectByPage(@Param("begin")int begin,@Param("size") int size); @Select("select count(*) from books") int selectTotalCount(); List<Book> selectByPageAndCondition(@Param("begin") int begin,@Param("size") int size,@Param("book") Book book); int selectTotalCountByCondition(Book book); @Update("update books set bookName = #{bookName}, writer = #{writer},user = #{user}, number = #{number}, state = #{state} where id = #{id}") void updateById(Book book);}
2.BookMapper.xml
代码如下(示例):
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.MyJavaClass.mapper.BookMapper"> <select id="selectBycondition" resultType="com.MyJavaClass.pojo.Book"> select * from books <where> <if test=""></if> </where> </select> <delete id="deleteByIds"> delete from books where id in <foreach collection="ids" item="id" separator="," open="(" close=")"> #{id} </foreach> </delete> <select id="selectByPageAndCondition" resultType="com.MyJavaClass.pojo.Book"> select * from books <where> <if test="book.number != null and book.number != '' "> and number like #{book.number} </if> <if test="book.bookName != null and book.bookName != '' "> and bookName like #{book.bookName} </if> <if test="book.writer != null and book.writer != '' "> and writer like #{book.writer} </if> <if test="book.state != null"> and state = #{book.state} </if> </where> limit #{begin},#{size} </select> <select id="selectTotalCountByCondition" resultType="java.lang.Integer"> select count(*) from books <where> <if test="number != null and number != '' "> and number like #{number} </if> <if test="bookName != null and bookName != '' "> and bookName like #{bookName} </if> <if test="writer != null and writer != '' "> and writer like #{book.writer} </if> <if test="state != null"> and state = #{state} </if> </where> </select></mapper>
二、Book数据类型
1.Book.class
Integer id; String number; String bookName ; String writer ; String user ; Integer state ;
2.MySQL
id int PRIMARY KEY auto_increment, bookName varchar(20), writer varchar(20), user varchar(20), number varchar(20), state INT
三、Service层
1、Service接口
文件名:BookService
package com.MyJavaClass.service;import com.MyJavaClass.pojo.Book;import com.MyJavaClass.pojo.PageBean;import java.util.List;public interface BookService { List<Book> selectAll(); void add(Book book); void deleteByIds(int[] ids); PageBean<Book> selectByPage(int currentPage,int pageSize); PageBean<Book> selectByPageAndCondition(int currentPage,int pageSize,Book book); void updateById(Book book);}
2、Service实现类
文件名:BookServiceimpl
package com.MyJavaClass.service.impl;import com.MyJavaClass.mapper.BookMapper;import com.MyJavaClass.pojo.Book;import com.MyJavaClass.pojo.PageBean;import com.MyJavaClass.service.BookService;import com.MyJavaClass.util.SqlSessionFactoryUtils;import org.apache.ibatis.session.SqlSession;import org.apache.ibatis.session.SqlSessionFactory;import java.util.List;public class BookServiceimpl implements BookService { SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory(); public List<Book> selectAll(){ SqlSession sqlSession = factory.openSession(); BookMapper bookMapper = sqlSession.getMapper(BookMapper.class); List<Book> books = bookMapper.selectAll(); sqlSession.close(); return books; } public void add(Book book){ SqlSession sqlSession = factory.openSession(); BookMapper bookMapper = sqlSession.getMapper(BookMapper.class); bookMapper.add(book); sqlSession.commit(); sqlSession.close(); } public void deleteByIds(int[] ids){ SqlSession sqlSession = factory.openSession(); BookMapper bookMapper = sqlSession.getMapper(BookMapper.class); bookMapper.deleteByIds(ids); sqlSession.commit(); sqlSession.close(); } @Override public PageBean<Book> selectByPage(int currentPage, int pageSize) { SqlSession sqlSession = factory.openSession(); BookMapper bookMapper = sqlSession.getMapper(BookMapper.class); int begin = (currentPage - 1) * pageSize; int size = pageSize; List<Book> rows = bookMapper.selectByPage(begin,size); int totalCount = bookMapper.selectTotalCount(); PageBean<Book> pageBean = new PageBean<>(); pageBean.setRows(rows); pageBean.setTotalCount(totalCount); sqlSession.close(); return pageBean; } @Override public PageBean<Book> selectByPageAndCondition(int currentPage, int pageSize, Book book) { SqlSession sqlSession = factory.openSession(); BookMapper bookMapper = sqlSession.getMapper(BookMapper.class); int begin = (currentPage - 1) * pageSize; int size = pageSize; String number = book.getNumber(); if(number != null && number.length()>0){ book.setNumber("%" + number + "%"); } String bookName = book.getBookName(); if(bookName != null && bookName.length()>0){ book.setBookName("%" + bookName + "%"); } String writer = book.getWriter(); if(writer != null && writer.length()>0){ book.setWriter("%" + writer + "%"); } List<Book> rows = bookMapper.selectByPageAndCondition(begin,size,book); int totalCount = bookMapper.selectTotalCountByCondition(book); PageBean<Book> pageBean = new PageBean<>(); pageBean.setRows(rows); pageBean.setTotalCount(totalCount); sqlSession.close(); return pageBean; } public void updateById(Book book){ SqlSession sqlSession = factory.openSession(); BookMapper bookMapper = sqlSession.getMapper(BookMapper.class); bookMapper.updateById(book); sqlSession.commit(); sqlSession.close(); }}
四、Servlet层
文件名:BookServlet.class
package com.MyJavaClass.web;import com.MyJavaClass.pojo.Book;import com.MyJavaClass.pojo.PageBean;import com.MyJavaClass.service.BookService;import com.MyJavaClass.service.impl.BookServiceimpl;import com.alibaba.fastjson.JSON;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.BufferedReader;import java.io.IOException;import java.util.List;@WebServlet("/Book/*")public class BookServlet extends BaseServlet{ private BookService bookService = new BookServiceimpl(); public void selectAll(HttpServletRequest req, HttpServletResponse resp)throws ServletException,IOException{ List<Book> books = bookService.selectAll(); String jsonString = JSON.toJSONString(books); resp.setContentType("text/json;charset=utf-8"); resp.getWriter().write(jsonString); } public void add(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{ BufferedReader br = req.getReader(); String params = br.readLine(); Book book = JSON.parseObject(params,Book.class); bookService.add(book); resp.getWriter().write("success"); } public void deleteByIds(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{ BufferedReader br = req.getReader(); String params = br.readLine(); int[] ids = JSON.parseObject(params,int[].class); bookService.deleteByIds(ids); resp.getWriter().write("success"); } public void selectByPage(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{ String _currentPage = req.getParameter("currentPage"); String _pageSize = req.getParameter("pageSize"); int currentPage = Integer.parseInt(_currentPage); int pageSize = Integer.parseInt(_pageSize); //2. 调用service查询 PageBean<Book> pageBean = bookService.selectByPage(currentPage, pageSize); //2. 转为JSON String jsonString = JSON.toJSONString(pageBean); //3. 写数据 resp.setContentType("text/json;charset=utf-8"); resp.getWriter().write(jsonString); } public void selectByPageAndCondition(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{ String _currentPage = req.getParameter("currentPage"); String _pageSize = req.getParameter("pageSize"); int currentPage = Integer.parseInt(_currentPage); int pageSize = Integer.parseInt(_pageSize); BufferedReader br = req.getReader(); String params = br.readLine(); Book book = JSON.parseObject(params,Book.class); PageBean<Book> pageBean = bookService.selectByPageAndCondition(currentPage,pageSize,book); String jsonString = JSON.toJSONString(pageBean); resp.setContentType("text/json;charset=utf-8"); resp.getWriter().write(jsonString); } public void updateById(HttpServletRequest req,HttpServletResponse resp)throws ServletException,IOException{// String id = req.getParameter("id"); BufferedReader br = req.getReader(); String params = br.readLine(); Book book = JSON.parseObject(params, Book.class); if(book!=null){ System.out.println("ok"); System.out.println(book); } else System.out.println("no"); bookService.updateById(book); resp.getWriter().write("success"); }}
五、前端代码实现
文件名:Book.html
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title> <style> .el-table .warning-row { background: oldlace; } .el-table .success-row { background: #f0f9eb; } body{ background:url("img/p.png") no-repeat center top; background-size:cover; background-attachment:fixed; opacity:0.75; } </style></head><body><div id="app"> <!--搜索表单--> <el-form :inline="true" :model="book" class="demo-form-inline"> <el-form-item label="当前状态"> <el-select v-model="book.state" placeholder="当前状态"> <el-option label="在库中" value="1"></el-option> <el-option label="未在库中" value="0"></el-option> </el-select> </el-form-item> <el-form-item label="书籍编号"> <el-input v-model="book.number" placeholder="书籍编号"></el-input> </el-form-item> <el-form-item label="书籍名称"> <el-input v-model="book.bookName" placeholder="书籍名称"></el-input> </el-form-item> <el-form-item label="作者"> <el-input v-model="book.writer" placeholder="作者"></el-input> </el-form-item> <el-form-item> <el-button type="primary" @click="onSubmit">查询</el-button> </el-form-item> </el-form> <!--按钮--> <el-row> <el-button type="danger" plain @click="deleteByIds">批量删除</el-button> <el-button type="primary" plain @click="dialogVisible = true">新增</el-button> <el-button type="success" onclick="window.location.href='student.html'"plain>学生信息查询</el-button> </el-row> <!--添加数据对话框表单--> <el-dialog title="新增书籍" :visible.sync="dialogVisible" width="30%" > <el-form ref="form" :model="book" label-width="80px"> <el-form-item label="书籍编号"> <el-input v-model="book.number"></el-input> </el-form-item> <el-form-item label="书籍名称"> <el-input v-model="book.bookName"></el-input> </el-form-item> <el-form-item label="作者"> <el-input v-model="book.writer"></el-input> </el-form-item> <el-form-item label="借阅人"> <el-input v-model="book.user"></el-input> </el-form-item> <el-form-item label="状态"> <el-switch v-model="book.state" active-value="1" inactive-value="0" ></el-switch> </el-form-item> <el-form-item> <el-button type="primary" @click="addBrand">提交</el-button> <el-button @click="dialogVisible = false">取消</el-button> </el-form-item> </el-form> </el-dialog> <el-dialog title="修改书籍" :visible.sync="dialog2Visible" width="30%" > <el-form ref="form" :model="brandSelect" label-width="80px"> <el-form-item label="书籍编号"> <el-input v-model="brandSelect.number"></el-input> </el-form-item> <el-form-item label="书籍名称"> <el-input v-model="brandSelect.bookName"></el-input> </el-form-item> <el-form-item label="作者"> <el-input v-model="brandSelect.writer"></el-input> </el-form-item> <el-form-item label="借阅人"> <el-input v-model="brandSelect.user"></el-input> </el-form-item> <el-form-item label="状态"> <el-switch v-model="brandSelect.state" active-value="1" inactive-value="0" ></el-switch> </el-form-item> <el-form-item> <el-button type="primary" @click="update">提交</el-button> <el-button @click="dialog2Visible = false">取消</el-button> </el-form-item> </el-form> </el-dialog> <!--表格--> <template > <el-table :data="tableData" style="width: 100%" :row-class-name="tableRowClassName" @selection-change="handleSelectionChange" > <el-table-column type="selection" width="55"> </el-table-column> <el-table-column type="index" width="50"> </el-table-column> <el-table-column prop="number" label="书籍编号" align="center" > </el-table-column> <el-table-column prop="bookName" label="书籍名称" align="center" > </el-table-column> <el-table-column prop="writer" align="center" label="作者"> </el-table-column> <el-table-column prop="state" align="center" label="当前状态"> </el-table-column> <el-table-column prop="user" align="center" label="借阅人"> </el-table-column> <el-table-column align="center" label="操作"> <template slot-scope="scope"> <el-row> <el-button type="primary"@click="brandShow(scope.row)">修改</el-button> </el-row> </template> </el-table-column> </el-table> </template> <!--分页工具条--> <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[5, 10, 15, 20]" :page-size="5" layout="total, sizes, prev, pager, next, jumper" :total="totalCount"> </el-pagination></div><script src="js/axios-0.18.0.js"></script><script src="js/vue.js"></script><script src="element-ui/lib/index.js"></script><link rel="stylesheet" href="element-ui/lib/theme-chalk/index.css"><script> new Vue({ el: "#app", mounted(){<!-- //当页面加载完成后,发送异步请求,获取数据--><!-- var _this = this;--><!-- axios({--><!-- method:"get",--><!-- url:"http://localhost:8080/curriculumDesign/Book/selectAll"--><!-- }).then(function (resp) {--><!-- _this.tableData = resp.data;--><!-- })-->this.selectAll(); }, methods: { //根据id查询 selectAll(){ var _this = this;axios({ method:"post", url:"http://localhost:8080/curriculumDesign/Book/selectByPage?currentPage="+this.currentPage+"&pageSize=" + this.pageSize}).then(resp =>{ //设置表格数据 _this.tableData = resp.data.rows; // {rows:[],totalCount:100} //设置总记录数 _this.totalCount = resp.data.totalCount;})}, tableRowClassName({row, rowIndex}) { if (rowIndex === 1) { return 'warning-row'; } else if (rowIndex === 3) { return 'success-row'; } return ''; }, // 复选框选中后执行的方法 handleSelectionChange(val) { this.multipleSelection = val; console.log(this.multipleSelection) },brandShow(row) { // 获取数据 this.brandSelect = row; console.log(this.book); // 弹出窗口 this.dialog2Visible = true; console.log(this.dialog2Visible); this.selectAll();}, update(){ var _this = this; axios({ method:"post", url:"http://localhost:8080/curriculumDesign/Book/updateById", data:_this.brandSelect //这是提交的表单数据 }).then(function (resp){ //这里是success数据 if(resp.data == "success"){ //添加成功 _this.dialog2Visible = false; console.log("修改成功!"); //重新查询数据进行显示 _this.selectAll(); _this.$message({ message: '恭喜你,修改成功', type: 'success' }); } else{ _this.$message.error('修改失败'); } }) }, // 查询方法 onSubmit() { axios({ method:"post", url:"http://localhost:8080/curriculumDesign/Book/selectByPageAndCondition?currentPage="+this.currentPage+"&pageSize="+this.pageSize, data:this.book}).then((resp) => { //设置表格数据 this.tableData = resp.data.rows; // {rows:[],totalCount:100} //设置总记录数 this.totalCount = resp.data.totalCount;}) }, // 添加数据 addBrand(){ var _this = this; // 发送ajax请求,添加数据 axios({ method:"post", url:"http://localhost:8080/curriculumDesign/Book/add", data:_this.book }).then(function (resp) { //响应数据的处理逻辑 if(resp.data == "success"){ //添加成功 //关闭窗口 _this.dialogVisible = false; // 重新查询数据 _this.selectAll(); // 弹出消息提示 _this.$message({ message: '恭喜你,添加成功', type: 'success' }); } }) }, deleteByIds(){ // 弹出确认提示框 this.$confirm('此操作将删除该数据, 是否继续?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => { //用户点击确认按钮 //1. 创建id数组 [1,2,3], 从 this.multipleSelection 获取即可 for (let i = 0; i < this.multipleSelection.length; i++) { let selectionElement = this.multipleSelection[i]; this.selectedIds[i] = selectionElement.id; } //2. 发送AJAX请求 var _this = this; // 发送ajax请求,添加数据 axios({ method:"post", url:"http://localhost:8080/curriculumDesign/Book/deleteByIds", data:_this.selectedIds }).then(function (resp) { if(resp.data == "success"){ //删除成功 // 重新查询数据 _this.selectAll(); // 弹出消息提示 _this.$message({ message: '恭喜你,删除成功', type: 'success' }); } }) }).catch(() => { //用户点击取消按钮 this.$message({ type: 'info', message: '已取消删除' }); });}, //分页 handleSizeChange(val) { this.pageSize = val; this.selectAll(); }, handleCurrentChange(val) { this.currentPage = val; this.selectAll(); } }, data() { return { // 当前页码 // 每页显示的条数 pageSize:5, // 总记录数 totalCount:100, // 当前页码 currentPage: 1, // 添加数据对话框是否展示的标记 dialogVisible: false, dialog2Visible: false,<!-- Integer id;--><!-- String number;--><!-- --><!-- String bookName ;--><!-- String writer ;--><!-- String user ;--><!-- Integer state ;--> book:{ state:'', bookName:'', user:'', writer:'', number:"", id:"" }, brandSelect:{ state:'', bookName:'', user:'', writer:'', number:"", id:"" }, // 品牌模型数据 brand: { status: '', brandName: '', companyName: '', id:"", ordered:"", description:"" }, // 复选框选中数据集合 multipleSelection: [], selectedIds:[], // 表格数据 tableData: [{ number:"ccsu123", bookName: '华为', writer: '老人与海', state: '1', user:"唐涛", id:'1' }] } } })</script></body></html>
总结
以上就是全部代码了,做起来并不复杂,一两天就能做完,在熟练的情况下不到一天就能弄完。 页面如下文章来源:https://www.toymoban.com/news/detail-478202.html
文章来源地址https://www.toymoban.com/news/detail-478202.html
到了这里,关于JavaWeb图书管理系统课设:全面掌握CRUD操作的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!