(续)增删改查的完善

续着上次的增删改查 Springmvc+Springjdbc+Vue

数据库也是接着上次的
先上前端代码

<!DOCTYPE html>
<html>
	<head>
		<style type="text/css">
			table.gridtable {
     
				font-family: verdana, arial, sans-serif;
				font-size: 11px;
				color: #333333;
				border-width: 1px;
				border-color: #666666;
				border-collapse: collapse;
			}

			table.gridtable th {
     
				border-width: 1px;
				padding: 8px;
				border-style: solid;
				border-color: #666666;
				background-color: #dedede;
			}

			table.gridtable td {
     
				border-width: 1px;
				padding: 8px;
				border-style: solid;
				border-color: #666666;
				background-color: #ffffff;
			}

			.modalfade {
     
				text-align: center;
				outline: aqua;
				display: inline-block;
				visibility: hidden;
				top: -50px;
			}

			.close {
     
				float: right;
			}

			.modalfade2 {
     
				text-align: center;
				outline: aqua;
				position: relative;
				border-style: solid;
				border-color: burlywood;
				padding: 50px;
				margin-top: -355.35px;
				display: inline-block;
				visibility: hidden;
				top: -50px;
			}

			.close2 {
     
				float: right;
			}
		</style>
		<meta charset="utf-8" />
		<title></title>
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
		<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.0/axios.js"></script>
		<script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
	</head>
	<body>
		<div id="Books">
			<div>
				<table class="gridtable" align="center">
					<caption>图书信息表</caption>
					<thead>
						<tr>
							<th class="center">编号</th>
							<th class="center">书名</th>
							<th class="center">价格</th>
							<th class="center">图书信息</th>
							<th class="center">创建时间</th>
							<th class="center">修改时间</th>
							<th class="center">操作</th>
						</tr>
					</thead>
					<tbody>
						<tr v-for="(booklist,index) in books">
							<td class='center'>{
     {
     index+1}}</td>
							<td class='center'>{
     {
     booklist.name}}</td>
							<td class='center'>{
     {
     booklist.price}}</td>
							<td class="center">{
     {
     booklist.info}}</td>
							<td class='center'>{
     {
     booklist.create_time}}</td>
							<td class="center">{
     {
     booklist.update_time}}</td>
							<td class="center"><button class="btn" onclick="display(1)" @click="backShow(index)" data-toggle="modal"
								 data-target="#myModal">修改</button><button class="btn" @click="del(index,booklist.id)">删除</button></td>
						</tr>
					</tbody>
				</table>
				<div style="margin: 1.25rem;position: relative;text-align: center;">
					<input type="text" v-model="searchbookId" placeholder="请输入要查询书的编号" />
					<button @click="searchBook(searchbookId)">查询</button>
					<button style="margin-left: 50px;" onclick="display2(1)" >添加</button>
				</div>
			</div>
			<center>
				<div class="modalfade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
					<div class="modal-dialog" role="document">
						<div class="modal-content">
							<div class="modal-header">
								<button type="button" class="close" onclick="display(0)" id="clsbtn">&times;</button>
								<h4 class="modal-title" id="myModalLabel">修改商品</h4>
							</div>
							<div class="modal-body">
								<form id="updateForm" class="form-horizontal">
									<div class="form-group">
										<label class="col-sm-2 control-label">编号</label>
										<div class="col-sm-10">
											<input type="text" class="form-control" name="id" v-model="modifiybook.id" readonly="readonly" />
										</div>
									</div>
									<div class="form-group">
										<label class="col-sm-2 control-label">图书名称</label>
										<div class="col-sm-10">
											<input type="text" class="form-control" name="name" v-model="modifiybook.name" />
										</div>
									</div>
									<div class="form-group">
										<label class="col-sm-2 control-label">图书价格</label>
										<div class="col-sm-10">
											<input type="text" class="form-control" name="price" v-model="modifiybook.price" />
										</div>
									</div>
									<div class="form-group">
										<label class="col-sm-2 control-label">图书信息</label>
										<div class="col-sm-10">
											<input type="text" class="form-control" name="info" v-model="modifiybook.info" />
										</div>
									</div>
									<div class="form-group">
										<label class="col-sm-2 control-label" name="create_time">创建时间</label>
										<div class="col-sm-10">
											<input type="text" class="form-control" name="create_time" :value="modifiybook.create_time" readonly="readonly" />
										</div>
									</div>
									<div class="form-group">
										<label class="col-sm-2 control-label">修改时间</label>
										<div class="col-sm-10">
											<input type="text" class="form-control" name="update_time" :value="update_time|formatTime('YMDHMS')"
											 readonly="readonly" />
										</div>
									</div>
									<button @click="updatebook" type="button" @click="backShow(modifiybook.[index])">修改</button>
								</form>
							</div>
						</div>
					</div>
				</div>
			</center>
			<center>
				<div class="modalfade2" id="myModal2">
					<div class="modal-dialog" role="document">
						<div class="modal-content">
							<div class="modal-header">
								<button type="button" class="close" id="clsbtn2" onclick="display2(0)">&times;</button>
								<h4 class="modal-title">添加图书</h4>
							</div>
							<div class="modal-body">
								<form id="addForm" class="form-horizontal">
									<div class="form-group">
										<label class="col-sm-2 control-label">图书名称</label>
										<div class="col-sm-10">
											<input type="text" class="form-control" name="name" v-model="addbook.name" />
										</div>
									</div>
									<div class="form-group">
										<label class="col-sm-2 control-label">图书价格</label>
										<div class="col-sm-10">
											<input type="text" class="form-control" name="price" v-model="addbook.price" />
										</div>
									</div>
									<div class="form-group">
										<label class="col-sm-2 control-label">图书信息</label>
										<div class="col-sm-10">
											<input type="text" class="form-control" name="detail" v-model="addbook.info" />
										</div>
									</div>
									<div class="form-group">
										<label class="col-sm-2 control-label" name="create_time">创建时间</label>
										<div class="col-sm-10">
											<input type="text" class="form-control" name="create_time" :value="create_time|formatTime('YMDHMS')"
											 readonly="readonly" />
										</div>
									</div>
									<div class="form-group">
										<div class="col-sm-offset-2 col-sm-10">
											<button @click="addBook()" type="button" class="btn btn-primary" data-dismiss="modal">
												提交
											</button>
										</div>
									</div>
								</form>
							</div>
						</div>
					</div>
				</div>
			</center>
		</div>
		<script>
			function addZero(val) {
     
				if (val < 10) {
     
					return "0" + val;
				} else {
     
					return val;
				}
			};
			Vue.filter("formatTime", function(value, type) {
     
				var dataTime = "";
				var data = new Date();
				data.setTime(value);
				var year = data.getFullYear();
				var month = addZero(data.getMonth() + 1);
				var day = addZero(data.getDate());
				var hour = addZero(data.getHours());
				var minute = addZero(data.getMinutes());
				var second = addZero(data.getSeconds());
				if (type == "YMD") {
     
					dataTime = year + "-" + month + "-" + day;
				} else if (type == "YMDHMS") {
     
					dataTime = year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
				} else if (type == "HMS") {
     
					dataTime = hour + ":" + minute + ":" + second;
				} else if (type == "YM") {
     
					dataTime = year + "-" + month;

				}
				return dataTime; //将格式化后的字符串输出到前端显示
			});
			var app = new Vue({
     
				el: '#Books',
				data: {
     
					modifiybook: {
     },
					addbook: {
     },
					update_time: new Date,
					create_time: new Date,
					books: [],
					searchbookId: '',
				},
				mounted() {
     
					this.getbooklist();
				},
				methods: {
     
					getbooklist() {
     
						var that = this
						axios.post("http://localhost:8080/Shanzhiqiang_war/index/getAllBooks")
							.then(function(res) {
     
								console.log(res.data)
								that.books = res.data
							}).catch(function(err) {
     
								console.log(err)
							})
					},
					searchBook(searchbookId) {
     
						if (searchbookId != '') {
     
							var that = this
							console.log(searchbookId)
							axios.post("http://localhost:8080/Shanzhiqiang_war/index/searchBook", {
     
									"searchBookId": searchbookId
								})
								.then(function(res) {
     
									console.log(res.data)
									that.books = res.data
								})
						} else {
     
							this.getbooklist()
						}
					},
					addBook() {
     
						var that = this
						this.addbook.create_time = Vue.filter("formatTime")(this.create_time, "YMDHMS")
						console.log(this.addbook)
						axios.post("http://localhost:8080/Shanzhiqiang_war/index/addBook", that.addbook)
							.then(function(res) {
     
								console.log(res.data)
								if (res.data == 'success') {
     
									alert('添加成功')
									that.books.push(that.addbook)
								}else{
     
									alert('添加失败,继续改bug')
								}
							})

					},
					backShow(index) {
     
						console.log(index)
						this.modifiybook = this.books[index]
						console.log(this.modifiybook)
					},
					updatebook() {
     
						var that = this
						// modifiybook
						this.modifiybook.update_time = Vue.filter("formatTime")(this.update_time, "YMDHMS")
						console.log(this.modifiybook)
						axios.post("http://localhost:8080/Shanzhiqiang_war/index/updateBook", that.modifiybook)
							.then(function(res) {
     
								console.log(res.data)
								if (res.data == 'success') {
     
									alert('修改成功!')
									that.getbooklist()
								} else {
     
									alert('修改失败!继续改bug')
								}
							})
					},
					del(index, id) {
     
						var result = confirm("是否删除?");
						var that = this
						if (result) {
     
							axios.post("http://localhost:8080/Shanzhiqiang_war/index/deleteBook", {
     
									"selected": id
								})
								.then(function(res) {
     
									console.log(res.data)
									if (res.data == 'success') {
     
										alert('删除成功!')
										that.books.splice(index, 1)
									} else {
     
										alert('删除失败!继续改bug')
									}
								}).catch(function(err) {
     
									console.log(err.data)
								})
						}
					},
				}
			})

			var modal = document.getElementById("myModal");
			var modal2 = document.getElementById("myModal2");

			function display(x) {
     
				if (x == 1) {
     
					modal.style.visibility = "visible"
				}
				if (x == 0) {
     
					modal.style.visibility = "hidden"
				}
			}

			function display2(x) {
     
				if (x == 1) {
     
					modal2.style.visibility = "visible"
				}
				if (x == 0) {
     
					modal2.style.visibility = "hidden"
				}
			}
		</script>
	</body>
</html>

后端:
(续)增删改查的完善_第1张图片

package controller;


import com.fasterxml.jackson.annotation.JsonFormat;
import entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import service.BookServiceImpl;

import java.util.List;
import java.util.Map;


@RequestMapping("/index")
@Controller
@CrossOrigin(origins = "*", maxAge = 3600)
public class BookControl {
     


     @Autowired
     BookServiceImpl bookService;
     List<Book> books;

     @ResponseBody
     @RequestMapping("/getAllBooks")
     public List<Book> selectAll(Model model) {
     
        books = bookService.selectAll();
        model.addAttribute("books",books);
        return books;
    }

    @ResponseBody
    @RequestMapping("/searchBook")
    public List<Book> searchBook(@RequestBody Map<String,Integer> addBook,Model model){
     
         System.out.println(addBook.get("searchBookId"));
        List<Book> book = bookService.selectByID(addBook.get("searchBookId"));
        model.addAttribute("Books",book);
        return book;
    }

    @ResponseBody
    @RequestMapping("/addBook")
    public String addBook(@RequestBody Book addBook,Model model){
     
         System.out.println(addBook);
        boolean result = bookService.add(addBook);
        if (result) {
     
            model.addAttribute("msg", "");
            return "success";
        } else {
     
            model.addAttribute("msg", "");
            return "fail";
        }
    }

    @ResponseBody
    @RequestMapping("/deleteBook")
    public String deleteBook(@RequestBody Map<String,Integer> del){
     
         System.out.println(del);
        boolean result = bookService.delete(del.get("selected"));
        if (result==true) return "success";
        else return "fail";
    }

    @ResponseBody
    @RequestMapping("/updateBook")
    public String updateBook(@RequestBody Book updateBook,Model model){
     
         System.out.println(updateBook);
        boolean result = bookService.update(updateBook);
        if (result) {
     
            model.addAttribute("msg", "");
            return "success";
        } else {
     
            model.addAttribute("msg", "");
            return "fail";
        }
    }

    

//    @ResponseBody //直接返回字符串 只能返回字符串
//    @RequestMapping("/index")
//    public String login(){
     
//        return "login";
//    }
//    @RequestMapping("commit")
//    public  String commit(String uername,String password){
     
//        System.out.println("username:" +uername);
//        System.out.println("password:" + password);
//        return "success";
//    }
}

然后Dao层

package dao;

import entity.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class BookDaoImpl implements BookDao{
     

    RowMapper<Book> rowMapper = new BeanPropertyRowMapper<Book>(Book.class);
    

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public boolean add(Book book) {
     
        String sql = "insert into bookinfo(name,price,info,create_time) value(?,?,?,?)";
        int result = jdbcTemplate.update(sql,new Object[]{
     
                book.getName(), book.getPrice(), book.getInfo(),book.getCreate_time()});
        System.out.println(result);
        if (result == 1) {
     
            return true;
        } else{
     
            return false;
        }
    }

    @Override
    public List<Book> selectAll() {
     
        String sql = "select * from bookinfo";
        List<Book> books = jdbcTemplate.query(sql,rowMapper);
        return books;
    }

    @Override
    public boolean update(Book updateBook) {
     
        String sql = "update bookinfo set name = ? ,price = ?,info = ?,update_time = ? where id = ?";
        int result = jdbcTemplate.update(sql,new Object[]{
     
            updateBook.getName(),updateBook.getPrice(),updateBook.getInfo(),updateBook.getUpdate_time(),updateBook.getId()
        });
        System.out.println(result);
        if (result == 1) {
     
            return true;
        } else{
     
            return false;
        }
    }

    @Override
    public boolean delete(Integer id) {
     
        String sql = "delete from bookinfo where id = ?";
        int result = jdbcTemplate.update(sql,id);
        System.out.println(result);
        if (result == 1) {
     
            return true;
        } else{
     
            return false;
        }
    }

    @Override
    public List<Book> selectByID(Integer id) {
     
        String sql = "select * from bookinfo where id =? ";
        List<Book> book =  jdbcTemplate.query(sql,new Object[]{
     id},rowMapper);
        return book;
    }
}

其余的都一样,跨域访问,简单的Vue实现增删改查 最近在学习Vue 没什么时间发 等Vue学的差不多了 发一个总结吧

你可能感兴趣的:(java,spring,node.js,vue.js,javascript)