1. 程式人生 > >書城後臺管理的增刪改查功能以及分頁實現

書城後臺管理的增刪改查功能以及分頁實現

 

點選圖書管理按鈕進入圖書管理列表

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<div>
	<a href="BookServlet?method=getBooksByPage">圖書管理</a>
	<a href="pages/manager/order_manager.jsp">訂單管理</a>
	<a href="index.jsp">返回商城</a>
</div>

對於根據頁面值傳送請求還是第一次進入頁面的請求做了判斷,判斷如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>圖書管理</title>
<%@ include file="/WEB-INF/include/base.jsp" %>
<script type="text/javascript">
	$(function(){
		$(".dela").click(function(){
// 			var title = $(this).parents("tr").children().html();
			var title = $(this).attr("id");
			if(confirm("確定刪除【"+title+"】嗎?") == false){
				return false;
			}
		});
		
		//實現確定按鈕分頁查詢
		$("#sub_page").click(function(){
			//取pageNo值
			var pageNo = $("#pn_input").val();
			//請求BookServlet
			location = "BookServlet?method=getBooksByPage&pageNo="+pageNo;
		});
		
	});
</script>
</head>
<body>
	
	<div id="header">
			<img class="logo_img" alt="" src="static/img/logo.gif" >
			<span class="wel_word">圖書管理系統</span>
			<%@ include file="/WEB-INF/include/header.jsp" %>
	</div>
	
	<div id="main">
		<table>
			<tr>
				<td>名稱</td>
				<td>價格</td>
				<td>作者</td>
				<td>銷量</td>
				<td>庫存</td>
				<td colspan="2">操作</td>
			</tr>	
			<c:forEach items="${requestScope.page.list }" var="book">
				<tr>
					<td>${book.title }</td>
					<td>${book.price }</td>
					<td>${book.author }</td>
					<td>${book.sales }</td>
					<td>${book.stock }</td>
					<td><a href="BookServlet?method=getBookById&bookId=${book.id }">修改</a></td>
					<td><a class="dela" id="${book.title }" href="BookServlet?method=delBookById&bookId=${book.id }">刪除</a></td>
				</tr>	
			</c:forEach>
			<tr>
				<td></td>
				<td></td>
				<td></td>
				<td></td>
				<td></td>
				<td></td>
				<td><a href="pages/manager/book_update.jsp">新增圖書</a></td>
			</tr>	
		</table>
		<br>
		<br>
		<div id="page_nav">
			<a href="BookServlet?method=getBooksByPage&pageNo=1">首頁</a>
			<c:if test="${page.pageNo>1 }">
				<a href="BookServlet?method=getBooksByPage&pageNo=${page.pageNo-1 }">上一頁</a>
			</c:if>
			<c:if test="${page.pageNo<page.totalPageNo }">
				<a href="BookServlet?method=getBooksByPage&pageNo=${page.pageNo+1 }">下一頁</a>
			</c:if>
			<a href="BookServlet?method=getBooksByPage&pageNo=${page.totalPageNo }">末頁</a>
			共${requestScope.page.pageNo }/${requestScope.page.totalPageNo }頁,${requestScope.page.totalRecord}條記錄
			 到第<input value="${requestScope.page.pageNo }" name="pn" id="pn_input"/>頁
			<input id="sub_page" type="button" value="確定">	
		</div>
		
	</div>
	
	<div id="bottom">
		<span>
			尚矽谷書城.Copyright &copy;2015
		</span>
	</div>
</body>
</html>

package com.atguigu.bean;

import java.io.Serializable;
import java.util.List;

public class Page<T> implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	//   5/19	
	private int pageNo;						//當前頁碼					使用者
	private int totalPageNo;				//總頁數=總條數/每頁顯示的個數	計算
	private int totalRecord;				//總條數					dao,sql:select count(*) from books
	public static final int PAGE_SIZE = 4;	//每頁顯示的個數				靜態常量
	private List<T> list;					//當前頁的資料集合			dao,sql:SELECT * FROM books LIMIT (pageNo-1)*PAGE_SIZE,PAGE_SIZE
	
	public int getPageNo() {
		if(pageNo < 1) {
			return 1;
		}
		if(pageNo > getTotalPageNo()) {
			return getTotalPageNo();
		}
		return pageNo;
	}
	public void setPageNo(int pageNo) {
		this.pageNo = pageNo;
	}
	/**
	 * 計算總頁數
	 * @return
	 */
	public int getTotalPageNo() {
		return totalRecord%PAGE_SIZE==0?totalRecord/PAGE_SIZE:totalRecord/PAGE_SIZE+1;
	}
	public void setTotalPageNo(int totalPageNo) {
		this.totalPageNo = totalPageNo;
	}
	public int getTotalRecord() {
		return totalRecord;
	}
	public void setTotalRecord(int totalRecord) {
		this.totalRecord = totalRecord;
	}
	public List<T> getList() {
		return list;
	}
	public void setList(List<T> list) {
		this.list = list;
	}
//	public static int getPageSize() {
//		return PAGE_SIZE;
//	}
	public Page(int pageNo, int totalPageNo, int totalRecord, List<T> list) {
		super();
		this.pageNo = pageNo;
		this.totalPageNo = totalPageNo;
		this.totalRecord = totalRecord;
		this.list = list;
	}
	public Page() {
		super();
		// TODO Auto-generated constructor stub
	}
	@Override
	public String toString() {
		return "Page [pageNo=" + pageNo + ", totalPageNo=" + totalPageNo + ", totalRecord=" + totalRecord + ", list="
				+ list + "]";
	}
	
}
package com.atguigu.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atguigu.bean.Book;
import com.atguigu.bean.Page;
import com.atguigu.service.BookService;
import com.atguigu.service.impl.BookServiceImpl;

/**
 * Servlet implementation class BookServlet
 */
public class BookServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
    
	private BookService bookService = new BookServiceImpl();
	/**
	 * 查詢所有book資訊
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
//	protected void getAllBooks(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		//取值(不用)
//		//呼叫service中的相應方法
//		List<Book> books = bookService.getAllBooks();
//		//將books存放到域中
//		request.setAttribute("books",books);
//		//跳轉,book_manager.jsp
//		request.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(request, response);
//	}
	/**
	 * 分頁查詢book
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void getBooksByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//取值
		String pageNo = request.getParameter("pageNo");
		//呼叫service
		Page<Book> page = bookService.getBookByPage(pageNo);
		//將page存放到域中
		request.setAttribute("page", page);
		//跳轉
		request.getRequestDispatcher("/pages/manager/book_manager.jsp").forward(request, response);
	}
	
	/**
	 * 新增book資訊
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void delBookById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//取值
		String bookId = request.getParameter("bookId");
		//呼叫service
		bookService.delBookById(bookId);
		//跳轉
		response.sendRedirect(request.getContextPath()+"/BookServlet?method=getBooksByPage");
	}
	
	
	/**
	 * 通過id獲取book資訊
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void getBookById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//取bookid值
		String id = request.getParameter("bookId");
		//呼叫Service
		Book book = bookService.getBookById(id);
		//將book存放域中
		request.setAttribute("book", book);
		//跳轉,book_update.jsp
		request.getRequestDispatcher("/pages/manager/book_update.jsp").forward(request, response);
	}
	
	/**
	 * 新增book資訊
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
//	protected void addBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//		//取值
//		String title = request.getParameter("title");
//		String author = request.getParameter("author");
//		String price = request.getParameter("price");
//		String sales = request.getParameter("sales");
//		String stock = request.getParameter("stock");
//		//呼叫service
//		bookService.addBook(new Book(null, title, author, Double.parseDouble(price), Integer.parseInt(sales), Integer.parseInt(stock), null));
//		//跳轉,重新查詢,book_manager.jsp
////		getAllBooks(request, response);
//		response.sendRedirect(request.getContextPath()+"/BookServlet?method=getAllBooks");
//	}
	/**
	 * 通過id獲取book資訊
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void updateBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//取值
		String id = request.getParameter("bookId");
		String title = request.getParameter("title");
		String author = request.getParameter("author");
		String price = request.getParameter("price");
		String sales = request.getParameter("sales");
		String stock = request.getParameter("stock");
		//通過判斷id值是否為空,執行相應方法
		//呼叫service
		if(id == null || "".equals(id)) {
			//呼叫addBook()
			bookService.addBook(new Book(null, title, author, Double.parseDouble(price), Integer.parseInt(sales), Integer.parseInt(stock), null));
		}else {
			//呼叫updateBook()
			bookService.updateBook(new Book(Integer.parseInt(id), title, author, Double.parseDouble(price), Integer.parseInt(sales), Integer.parseInt(stock), null));
		}
		//跳轉
		response.sendRedirect(request.getContextPath()+"/BookServlet?method=getBooksByPage");
	}
	
	
}
package com.atguigu.service.impl;

import java.util.List;

import com.atguigu.bean.Book;
import com.atguigu.bean.Page;
import com.atguigu.dao.BookDao;
import com.atguigu.dao.impl.BookDaoImpl;
import com.atguigu.service.BookService;

public class BookServiceImpl implements BookService {

	private BookDao bookDao = new BookDaoImpl();
	
	@Override
	public List<Book> getAllBooks() {
		return bookDao.getAllBooks();
	}

	@Override
	public void addBook(Book book) {
		bookDao.addBook(book);
	}

	@Override
	public void delBookById(String id) {
		bookDao.delBookById(id);
	}

	@Override
	public Book getBookById(String id) {
		return bookDao.getBookById(id);
	}

	@Override
	public void updateBook(Book book) {
		bookDao.updateBook(book);
	}

	@Override
	public Page<Book> getBookByPage(String pageNo) {
		Page<Book> page = new Page<Book>();
		int pNo = 1;//先設定為1,保證第一次訪問頁面時有值
		try {
			//若傳入的有具體的值,就按具體的值來pageNo為String型別的Integer.parseInt(PageNo)
			//萬一不可預知原因PageNo為null,那麼程式直接崩掉,防止這個捕獲一下
			pNo = Integer.parseInt(pageNo);
		} catch (NumberFormatException e) {
//			e.printStackTrace();
		}
		page.setPageNo(pNo);
		return bookDao.getBooksByPage(page);
	}

	@Override
	public Page<Book> getBookByPageAndPrice(String pageNo, String min, String max) {
		Page<Book> page = new Page<Book>();
		int pNo = 1;
		try {
			pNo = Integer.parseInt(pageNo);
		} catch (NumberFormatException e) {
//			e.printStackTrace();
		}
		page.setPageNo(pNo);
		//處理min,max
		double minEnd = 0;
		double maxEnd = Double.MAX_VALUE;
		try {
			minEnd = Double.parseDouble(min);
			maxEnd = Double.parseDouble(max);
			//交換值
			double temp=0;
			if(minEnd > maxEnd) {
				temp = minEnd;
				minEnd = maxEnd;
				maxEnd = temp;
			}
		} catch (NumberFormatException e) {
//			e.printStackTrace();
		}
		return bookDao.getBooksByPageAndPrice(page, minEnd, maxEnd);
	}

}
package com.atguigu.dao.impl;

import java.util.List;

import com.atguigu.bean.Book;
import com.atguigu.bean.Page;
import com.atguigu.dao.BaseDao;
import com.atguigu.dao.BookDao;

public class BookDaoImpl extends BaseDao<Book> implements BookDao {

	@Override
	public List<Book> getAllBooks() {
		String sql = "SELECT id,title,author,price,sales,stock,img_path FROM books";
		return this.getBeanList(sql);
	}

	@Override
	public void addBook(Book book) {
		String sql = "insert into books(title,author,price,sales,stock,img_path) values(?,?,?,?,?,?)";
		this.update(sql, book.getTitle(),book.getAuthor(),book.getPrice(),book.getSales(),book.getStock(),book.getImgPath());
	}

	@Override
	public void delBookById(String id) {
		String sql = "delete from books where id = ?";
		this.update(sql, id);
	}

	@Override
	public Book getBookById(String id) {
		String sql = "SELECT id,title,author,price,sales,stock,img_path FROM books WHERE id = ?";
		return this.getBean(sql, id);
	}

	@Override
	public void updateBook(Book book) {
		String sql = "update books set title=?,author=?,price=?,sales=?,stock=? where id=?";
		this.update(sql, book.getTitle(),book.getAuthor(),book.getPrice(),book.getSales(),book.getStock(),book.getId());
	}
	@Override
	public void updateBook(int stock, int sales, int id) {
		String sql = "update books set sales=?,stock=? where id=?";
		this.update(sql,sales,stock,id);
	}
	@Override
	public void updateBook(Object[][] params) {
		String sql = "update books set sales=?,stock=? where id=?";
		this.batchUpdate(sql,params);
	}
	
	@Override
	public Page<Book> getBooksByPage(Page<Book> page) {
		//page:pageNo PAGE_SIZE totalPageNo
		//dao:totalRecord
		String sql = "select count(*) from books";
		//long(int) Integer.parse 強轉是為了防止報錯,this.getSingeValue(sql)返回值為long
		//long怎麼轉為Integer呢?先+""然後再進行轉換
		int count = Integer.parseInt(this.getSingeValue(sql)+"");  
		//將totalRecord賦值
		page.setTotalRecord(count);//資料總條數
//		System.out.println("record:"+page.getTotalRecord());
//		System.out.println("pageNo:"+page.getTotalPageNo());
		//dao:list
		String sql2 = "SELECT id,title,author,price,sales,stock,img_path "
				+ "FROM books "
				+ "WHERE 1=1 "
				+ "LIMIT ?,?";
		//pageNo頁從(page.getPageNo()-1)*Page開始為第一條資料,Page.PAGE_SIZE為一頁展示多少條資料
		List<Book> list = this.getBeanList(sql2, (page.getPageNo()-1)*Page.PAGE_SIZE,Page.PAGE_SIZE);
		//將list存放到page中
		page.setList(list);
		return page;
	}

	@Override
	public Page<Book> getBooksByPageAndPrice(Page<Book> page,double min,double max) {
		String sql = "SELECT count(*) "
				+ "FROM books "
				+ "WHERE 1=1 "
				+ "AND price BETWEEN ? AND ?";
		int count = Integer.parseInt(this.getSingeValue(sql, min,max)+"");  //long(int) Integer.parse
		//將totalRecord賦值
		page.setTotalRecord(count);
		//dao:list
		String sql2 = "SELECT id,title,author,price,sales,stock,img_path "
				+ "FROM books "
				+ "WHERE 1=1 "
				+ "AND price BETWEEN ? AND ? "
				+ "LIMIT ?,?";
		List<Book> list = this.getBeanList(sql2, min,max,(page.getPageNo()-1)*Page.PAGE_SIZE,Page.PAGE_SIZE);
		//將list存放到page中
		page.setList(list);
		return page;
	}


	
	
}