1. 新建一个名为Books的动态Web工程
1.1. 添加gson-2.8.5.jar
1.2. 编写Book.java
package com.bjbs.action;
import java.io.Serializable;
import java.util.Date;
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
private Date date;
public Book() {
}
public Book(int id, String name, Date date) {
this.id = id;
this.name = name;
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
1.3. 编写BookAction.java
package com.bjbs.action;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.Gson;
public class BookAction extends HttpServlet {
private static final long serialVersionUID = 1L;
private List<Book> books = new ArrayList<Book>();
public BookAction() {
books.add(new Book(1, "红楼梦", new Date()));
books.add(new Book(2, "三国演义", new Date()));
books.add(new Book(3, "水浒传", new Date()));
books.add(new Book(4, "西游记", new Date()));
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String flag = req.getParameter("flag");
String id = req.getParameter("id");
String name = req.getParameter("name");
System.out.println("flag = "+ flag + ", id = " + id);
if("delete".equals(flag)) {
Book removeBook = null;
for (Book book : books) {
if(book.getId() == Integer.parseInt(id)) {
removeBook = book;
break;
}
}
books.remove(removeBook);
}else if("update".equals(flag)) {
for (Book book : books) {
if(book.getId() == Integer.parseInt(id)) {
book.setName(new String(name.getBytes("ISO-8859-1"), "UTF-8"));
break;
}
}
}else if("add".equals(flag)) {
books.add(new Book(Integer.parseInt(id), new String(name.getBytes("ISO-8859-1"), "UTF-8"), new Date()));
}
resp.setContentType("text/html;charset=UTF-8");
Gson gson = new Gson();
resp.getWriter().write(gson.toJson(books));
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
1.4. 编写index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>图书管理案例</title>
<style type="text/css">
.grid {
margin: auto;
width: 500px;
text-align: center;
}
.grid table {
width: 100%;
border-collapse: collapse;
}
.grid th,td {
border: 1px dashed orange;
height: 35px;
line-height: 35px;
}
.grid th {
background-color: #FF5722;
}
.grid .book {
padding-bottom: 20px;
padding-top: 10px;
background-color: #FFB800;
}
.grid .total {
height: 30px;
line-height: 30px;
background-color: #1E9FFF;
border-top: 1px solid #C2D89A;
}
</style>
</head>
<body>
<div id="app">
<div class="grid">
<div>
<h1>图书管理</h1>
<div class="book">
<div>
<label for="id">编号: </label>
<input type="text" id="id" v-model='id' :disabled="flag" v-focus>
<label for="name">名称: </label>
<input type="text" id="name" v-model='name'>
<button @click='handle' :disabled="submitFlag">提交</button>
</div>
</div>
</div>
<div class="total">
<span>图书总数: </span>
<span>{{total}}</span>
</div>
<table>
<thead>
<tr>
<th>编号</th>
<th>名称</th>
<th>时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr :key='item.id' v-for='item in books'>
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date | format("yyyy-MM-dd hh:mm:ss")}}</td>
<td>
<a href="" @click.prevent='toEdit(item.id)'>修改</a>
<span>|</span>
<a href="" @click.prevent='deleteBook(item.id)'>删除</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/javascript" src="vue.min.js"></script>
<script type="text/javascript" src="axios.js"></script>
<script type="text/javascript">
axios.interceptors.response.use(function(res){
return res.data;
}, function(error){
console.log(error)
});
// 自定义指令
Vue.directive('focus', {
inserted: function (el) {
el.focus();
}
});
Vue.filter('format', function(date, format) {
date = new Date(date);
if (!date || date.toUTCString() == "Invalid Date") {
return "";
}
var map = {
"M": date.getMonth() + 1, // 月份
"d": date.getDate(), // 日
"h": date.getHours(), // 小时
"m": date.getMinutes(), // 分
"s": date.getSeconds(), // 秒
"q": Math.floor((date.getMonth() + 3) / 3), // 季度
"S": date.getMilliseconds() // 毫秒
};
format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
var v = map[t];
if (v !== undefined) {
if (all.length > 1) {
v = "0" + v;
v = v.substr(v.length - 2);
}
return v;
} else if (t === "y") {
return (date.getFullYear() + "").substr(4 - all.length);
}
return all;
});
return format;
});
var vm = new Vue({
el: "#app",
data: {
flag: false,
submitFlag: false,
id: '',
name: '',
books: []
},
methods: {
handle: async function(){
if(this.flag) {
// 编辑图书
this.books = await axios.get('ba.ation?flag=update&id=' + this.id + '&name=' + this.name);
this.flag = false;
}else{
// 添加图书
this.books = await axios.get('ba.ation?flag=add&id=' + this.id + '&name=' + this.name);
}
// 清空表单
this.id = '';
this.name = '';
},
toEdit: function(id){
// 禁止修改ID
this.flag = true;
// 根据ID查询出要编辑的数据
var book = this.books.filter(function(item){
return item.id == id;
});
// 把获取到的信息填充到表单
this.id = book[0].id;
this.name = book[0].name;
},
deleteBook: async function(id){
this.books = await axios.get('ba.ation?flag=delete&id=' + id);
},
queryData: async function(){
this.books = await axios.get('ba.ation');
}
},
watch: {
id: function(val) {
if(this.flag) return;
// 验证图书id是否已经存在
var flag = this.books.some(function(item){
return item.id == val;
});
if(flag) {
// 图书名称存在
this.submitFlag = true;
}else{
// 图书名称不存在
this.submitFlag = false;
}
}
},
computed: {
total: function(){
// 计算图书的总数
return this.books.length;
}
},
mounted: function(){
this.queryData();
}
});
</script>
</body>
</html>
1.5. 修改web.xml
1.6. 运行项目, 访问index.html