做为对单页面的学习和后期框架的应用来说,掌握基本(原始)的ajax方式实现CRUD尤为重要,做为一个教学案例希望对读者(尤其是初学者)希望能够起到一个抛砖引玉的作用,有不对的地方,还请多多批评。
页面效果:
项目结构:
数据库:
DAO:
public interface IBookDao {
String FIND_ALL="SELECT * FROM t_book";
String ADD_BOOK="INSERT INTO t_book(title,author,price) VALUES(?,?,?)";
String UPDATE_BOOK="UPDATE t_book SET title=?,author=?,price=? WHERE id=?";
String FIND_BOOK="SELECT * FROM t_book WHERE id=?";
String DELETE_BOOK="DELETE FROM t_book WHERE id=?";
List<Book> findAll();
int add(Book book);
int update(Book book);
Book findById(int id);
int delete(int id);
}
DAO实现:
public class BookDao implements IBookDao {
@Override
public List<Book> findAll() {
return BaseDao.findAll(FIND_ALL,Book.class);
}
@Override
public int add(Book book) {
return BaseDao.executeCommand(ADD_BOOK,book.getTitle(),book.getAuthor(),book.getPrice());
}
@Override
public int update(Book book) {
return BaseDao.executeCommand(UPDATE_BOOK,book.getTitle(),book.getAuthor(),book.getPrice(),book.getId());
}
@Override
public Book findById(int id) {
return BaseDao.findByObject(FIND_BOOK,Book.class,id);
}
@Override
public int delete(int id) {
return BaseDao.executeCommand(DELETE_BOOK,id);
}
}
Service:
public class BookService {
private final IBookDao bookDao = new BookDao();
public List<Book> findAll(){//传递
return this.bookDao.findAll();
}
public boolean save(Book book) {
System.out.println(".................."+book);
if(book.getId()==null || book.getId()==0){
return this.bookDao.add(book)==1;
}else{
return this.bookDao.update(book)==1;
}
}
public Book findById(int id) {
return this.bookDao.findById(id);
}
public boolean delete(int id){
return this.bookDao.delete(id)==1;
}
}
Servlet:
@WebServlet(urlPatterns = {"/books","/save","/findById","/delete"})
public class BookAction extends HttpServlet {
private final BookService bookService =new BookService();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
String url = req.getServletPath();
System.out.println(url);
switch (url){
case "/books": this.books(req,resp);break;
case "/save": this.save(req,resp); break;
case "/findById": this.findById(req,resp);break;
case "/delete":this.delete(req,resp);break;
}
}
private void books(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
out.print(JSON.toJSON(this.bookService.findAll()));
out.close();
}
private void save(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Map map= req.getParameterMap();
Book book=new Book();
try {
BeanUtils.populate(book,map);
PrintWriter out = resp.getWriter();
if(this.bookService.save(book)){
out.print(true);
}else{
out.print(false);
}
out.close();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
private void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String sid=req.getParameter("id");
int id=Integer.parseInt(sid);
PrintWriter out = resp.getWriter();
out.print(JSON.toJSON(this.bookService.findById(id)));
out.close();
}
private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String sid=req.getParameter("id");
int id=Integer.parseInt(sid);
PrintWriter out = resp.getWriter();
out.print(JSON.toJSON(this.bookService.delete(id)));
out.close();
}
}
前台jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="inc.jsp"%>
<html>
<head>
<title>单页面CRUD</title>
<script src="js/book.js"></script>
</head>
<body>
<div class="container">
<table class="table table-bordered table-hover">
</table>
<div id="save">
<form method="post">
<input type="hidden" name="id"><br>
书名:<input type="text" name="title"><br>
作者:<input type="text" name="author"><br>
价格:<input type="text" name="price"><br>
<button class="btn-success">保存</button>
</form>
</div>
</div>
</body>
</html>
前台js:
$(function () {
$("#save").hide();//隐藏保存的div
$.get(
"books",
function (obj) {
//alert(typeof (obj));
console.log(obj);//保证是集合
$("table").append("<tr><td>编号</td><td>书名</td><td>作者</td><td>价格</td><td><button class='btn-info'>添加</button></td></tr>");
for(var i in obj){
$("table").append("<tr><td>"+obj[i].id+"</td><td>"+obj[i].title+
"</td><td>"+obj[i].author+"</td><td>"+obj[i].price+
"</td><td><button class='btn-warning' value='"+obj[i].id+"'>删除</button><button class='btn-primary' value='"+obj[i].id+"'>修改</button></td></tr>");
}
//添加
$(".btn-info").click(function () {
$("#save").fadeIn(2000);
})
//删除
$(".btn-warning").click(function () {
alert($(this).val());
if(confirm("确认吗?")){
$.get(
"delete?id="+$(this).val(),
function (obj) {
if(obj){
alert("OK");
location.reload();
}else{
alert("Sorry");
}
},"json"
)
}
})
//修改的回显
$(".btn-primary").click(function () {
alert($(this).val());
$.get(
"findById",
{id:$(this).val()},
function (obj) {
console.log(obj);
$("#save").fadeIn(2000);//显示修改的表单
//将各个属性的值回显到表单中
$("[name='id']").val(obj.id);//回显id
$("[name='title']").val(obj.title);//回显书名
$("[name='author']").val(obj.author);//回显作者
$("[name='price']").val(obj.price);//回显价格
},"json"
)
})
//保存
$(".btn-success").click(function () {
$.getJSON(
"save",
$("form").serialize(),//序列化表单
function (obj) {
if(obj){
alert("成功!");
location.reload();
}else{
alert("对不起,失败了!");
}
}
)
})
},"json"
)
})