前言
最近寫了個(gè)課設(shè),剛好剛學(xué)完javaweb需要鞏固一下,課設(shè)內(nèi)容是java增刪改查,想睡覺有人送枕頭了屬于是,這里我是實(shí)現(xiàn)了增刪改查,刪除那里我就偷懶了,只寫了批量刪除。(實(shí)際上就是黑馬項(xiàng)目套皮,不過我實(shí)現(xiàn)了修改功能,還是有點(diǎn)價(jià)值滴)
項(xiàng)目邏輯
后端寫好Servlet服務(wù),前端通過ajax申請(qǐng)服務(wù),并將表中數(shù)據(jù)通過Servlet與后臺(tái)數(shù)據(jù)庫交互,從而達(dá)到前端和后端互通的效果。
一、Mapper層實(shí)現(xiàn)代碼
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數(shù)據(jù)類型
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實(shí)現(xiàn)類
文件名: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. 調(diào)用service查詢 PageBean<Book> pageBean = bookService.selectByPage(currentPage, pageSize); //2. 轉(zhuǎn)為JSON String jsonString = JSON.toJSONString(pageBean); //3. 寫數(shù)據(jù) 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"); }}
五、前端代碼實(shí)現(xiàn)
文件名: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="當(dāng)前狀態(tài)"> <el-select v-model="book.state" placeholder="當(dāng)前狀態(tài)"> <el-option label="在庫中" value="1"></el-option> <el-option label="未在庫中" value="0"></el-option> </el-select> </el-form-item> <el-form-item label="書籍編號(hào)"> <el-input v-model="book.number" placeholder="書籍編號(hào)"></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>學(xué)生信息查詢</el-button> </el-row> <!--添加數(shù)據(jù)對(duì)話框表單--> <el-dialog title="新增書籍" :visible.sync="dialogVisible" width="30%" > <el-form ref="form" :model="book" label-width="80px"> <el-form-item label="書籍編號(hào)"> <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="狀態(tài)"> <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="書籍編號(hào)"> <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="狀態(tài)"> <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="書籍編號(hào)" 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="當(dāng)前狀態(tài)"> </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(){<!-- //當(dāng)頁面加載完成后,發(fā)送異步請(qǐng)求,獲取數(shù)據(jù)--><!-- var _this = this;--><!-- axios({--><!-- method:"get",--><!-- url:"http://localhost:8080/curriculumDesign/Book/selectAll"--><!-- }).then(function (resp) {--><!-- _this.tableData = resp.data;--><!-- })-->this.selectAll(); }, methods: { //根據(jù)id查詢 selectAll(){ var _this = this;axios({ method:"post", url:"http://localhost:8080/curriculumDesign/Book/selectByPage?currentPage="+this.currentPage+"&pageSize=" + this.pageSize}).then(resp =>{ //設(shè)置表格數(shù)據(jù) _this.tableData = resp.data.rows; // {rows:[],totalCount:100} //設(shè)置總記錄數(shù) _this.totalCount = resp.data.totalCount;})}, tableRowClassName({row, rowIndex}) { if (rowIndex === 1) { return 'warning-row'; } else if (rowIndex === 3) { return 'success-row'; } return ''; }, // 復(fù)選框選中后執(zhí)行的方法 handleSelectionChange(val) { this.multipleSelection = val; console.log(this.multipleSelection) },brandShow(row) { // 獲取數(shù)據(jù) 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 //這是提交的表單數(shù)據(jù) }).then(function (resp){ //這里是success數(shù)據(jù) if(resp.data == "success"){ //添加成功 _this.dialog2Visible = false; console.log("修改成功!"); //重新查詢數(shù)據(jù)進(jìn)行顯示 _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) => { //設(shè)置表格數(shù)據(jù) this.tableData = resp.data.rows; // {rows:[],totalCount:100} //設(shè)置總記錄數(shù) this.totalCount = resp.data.totalCount;}) }, // 添加數(shù)據(jù) addBrand(){ var _this = this; // 發(fā)送ajax請(qǐng)求,添加數(shù)據(jù) axios({ method:"post", url:"http://localhost:8080/curriculumDesign/Book/add", data:_this.book }).then(function (resp) { //響應(yīng)數(shù)據(jù)的處理邏輯 if(resp.data == "success"){ //添加成功 //關(guān)閉窗口 _this.dialogVisible = false; // 重新查詢數(shù)據(jù) _this.selectAll(); // 彈出消息提示 _this.$message({ message: '恭喜你,添加成功', type: 'success' }); } }) }, deleteByIds(){ // 彈出確認(rèn)提示框 this.$confirm('此操作將刪除該數(shù)據(jù), 是否繼續(xù)?', '提示', { confirmButtonText: '確定', cancelButtonText: '取消', type: 'warning' }).then(() => { //用戶點(diǎn)擊確認(rèn)按鈕 //1. 創(chuàng)建id數(shù)組 [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. 發(fā)送AJAX請(qǐng)求 var _this = this; // 發(fā)送ajax請(qǐng)求,添加數(shù)據(jù) axios({ method:"post", url:"http://localhost:8080/curriculumDesign/Book/deleteByIds", data:_this.selectedIds }).then(function (resp) { if(resp.data == "success"){ //刪除成功 // 重新查詢數(shù)據(jù) _this.selectAll(); // 彈出消息提示 _this.$message({ message: '恭喜你,刪除成功', type: 'success' }); } }) }).catch(() => { //用戶點(diǎn)擊取消按鈕 this.$message({ type: 'info', message: '已取消刪除' }); });}, //分頁 handleSizeChange(val) { this.pageSize = val; this.selectAll(); }, handleCurrentChange(val) { this.currentPage = val; this.selectAll(); } }, data() { return { // 當(dāng)前頁碼 // 每頁顯示的條數(shù) pageSize:5, // 總記錄數(shù) totalCount:100, // 當(dāng)前頁碼 currentPage: 1, // 添加數(shù)據(jù)對(duì)話框是否展示的標(biāo)記 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:"" }, // 品牌模型數(shù)據(jù) brand: { status: '', brandName: '', companyName: '', id:"", ordered:"", description:"" }, // 復(fù)選框選中數(shù)據(jù)集合 multipleSelection: [], selectedIds:[], // 表格數(shù)據(jù) tableData: [{ number:"ccsu123", bookName: '華為', writer: '老人與海', state: '1', user:"唐濤", id:'1' }] } } })</script></body></html>
總結(jié)
以上就是全部代碼了,做起來并不復(fù)雜,一兩天就能做完,在熟練的情況下不到一天就能弄完。 頁面如下文章來源:http://www.zghlxwxcb.cn/news/detail-478202.html
文章來源地址http://www.zghlxwxcb.cn/news/detail-478202.html
到了這里,關(guān)于JavaWeb圖書管理系統(tǒng)課設(shè):全面掌握CRUD操作的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!