实现图书增删改查和分页显示图书信息
生活随笔
收集整理的這篇文章主要介紹了
实现图书增删改查和分页显示图书信息
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
目錄
列:實現(xiàn)圖書增刪改查和分頁顯示圖書信息
效果截圖:
添加圖書?
分頁顯示
上傳圖片
修改
實現(xiàn)
導包
數(shù)據(jù)庫連接
db.properties
UploadServlet圖片上傳
封裝book數(shù)據(jù)
封裝分頁
BookDao.java 實現(xiàn)圖書增刪改查、分頁
BookDaoImp.java?
BookService接口 實現(xiàn)增刪改查、分頁
BookServiceImpl
addbook.jsp添加和修改圖書界面
BookAddServlet.java 提交添加的圖書信息
booklist.jsp查詢圖書與分頁顯示界面
BookQueryAllServlet 查詢數(shù)據(jù)和分頁請求
BookEditServlet 點擊修改時,獲取要修改的圖書id
updatebook.jsp 修改界面 在頁面顯示原有圖書信息
BookUpdateServlet修改圖書
BookDeleteServlet刪除圖書
TestBookManager測試類 添加圖書
列:實現(xiàn)圖書增刪改查和分頁顯示圖書信息
效果截圖:
添加圖書
分頁顯示
上傳圖片
修改
實現(xiàn)
導包
數(shù)據(jù)庫連接
import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties;public class DBUTils {public static String driver;public static String url;public static String user;public static String password;public static Properties prop;static {try {prop = new Properties();prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));driver = prop.getProperty("driver");url = prop.getProperty("url");user = prop.getProperty("username");password = prop.getProperty("password");System.out.println("driver" + driver + "\n" + "url" + url + "\n" + "username" + user + "\n" + "password" + password);} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}public static Connection getConn() {try {Class.forName(driver);Connection conn = DriverManager.getConnection(url, user, password);System.out.println("conn" + conn);return conn;} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}return null;} }db.properties
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/00web?characterEncoding=UTF-8 username=root password=123UploadServlet圖片上傳
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List;import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload;import com.demo.po.Book; import com.demo.service.BookService; import com.demo.service.BookServiceImpl;import sun.nio.ch.FileKey;/*** Servlet implementation class UploadServlet*/public class UploadServlet extends HttpServlet {private static final long serialVersionUID = 1L;private BookService bookService=new BookServiceImpl();/*** 解析上傳的圖片路徑 圖片的信息*/// aaa.doprotected void doPost(HttpServletRequest request, HttpServletResponse resp) throws IOException, ServletException {request.setAttribute("message", "");request.setAttribute("path", "");String path;String filename = null;// 設(shè)置上傳圖片的保存路徑String savePath = this.getServletContext().getRealPath("/images");File file = new File(savePath);// 判斷上傳文件的保存目錄是否存在if (!file.exists() && !file.isDirectory()) {System.out.println(savePath + "目錄不存在,需要創(chuàng)建");// 創(chuàng)建目錄file.mkdir();}DiskFileItemFactory factory = new DiskFileItemFactory();// 2、創(chuàng)建一個文件上傳解析器ServletFileUpload upload = new ServletFileUpload(factory);upload.setHeaderEncoding("UTF-8");// 3、判斷提交上來的數(shù)據(jù)是否是上傳表單的數(shù)據(jù)if (!ServletFileUpload.isMultipartContent(request)) {// 按照傳統(tǒng)方式獲取數(shù)據(jù)return;} try {List<FileItem> list = upload.parseRequest(request);System.out.println("----list"+list.toString());// 文件的路徑 以及保存的路徑for (FileItem item : list) {filename = item.getName();// 獲得一個項的文件名稱if (filename == null || filename.trim().equals("")) {// 如果為空則跳過continue;}// 報錯 需要過濾文件名稱 java.io.FileNotFoundException:// G:\測試02\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\FaceUp\WEB-INF\images\C:\Users\Ray\Pictures\2.jpeg// (文件名、目錄名或卷標語法不正確。)filename = filename.substring(filename.lastIndexOf("\\") + 1); // System.out.print(filename);if (filename.substring(filename.lastIndexOf(".") + 1).equals("png")|| filename.substring(filename.lastIndexOf(".") + 1).equals("jpg")|| filename.substring(filename.lastIndexOf(".") + 1).equals("jpeg")) {InputStream in = item.getInputStream();// 獲取上傳的輸入流FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);// 指 定web-inf目錄下的images文件request.setAttribute("path", "images" + "\\" + filename);System.out.println("-------圖片的路徑:"+savePath+ "\\" + filename);path=savePath+ "\\" + filename;int len = 0;byte buffer[] = new byte[1024];while ((len = in.read(buffer)) > 0)// 每次讀取{out.write(buffer, 0, len);}in.close();out.close();item.delete();request.setAttribute("message", "上傳成功"); /* //獲取http路徑String imgpath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();//D:\j2ee\javaeetask\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\0621crudorimg\String path02=request.getServletContext().getRealPath("/")+"images"+"\\";System.out.println("111111"+path02);*///添加圖片路徑到數(shù)據(jù)庫int id=Integer.parseInt(request.getParameter("id"));System.out.println("22222222222path"+path);// System.out.println("22222222222path"+imgpath);System.out.println("3333"+filename);Book book=new Book(filename);book.setId(id);int count=bookService.updateImg(book, id);} else { // 必須是圖片才能上傳否則失敗return;}}} catch (FileUploadException e) {e.printStackTrace();}resp.sendRedirect("query.do");}}封裝book數(shù)據(jù)
實現(xiàn)get、set、重寫equal、重寫hashCode、無參有償構(gòu)造方法、toString方法
封裝分頁
public class PageBean<T> {private Integer currentPage;// 當前頁碼private Integer allNum;// 總記錄數(shù)(記錄共多少條數(shù)據(jù))private Integer onePageNum;// 頁面大小(一頁的數(shù)據(jù))private Integer allPage;// 總頁數(shù)private List<T> beanList;// 當前頁數(shù)據(jù)顯示public Integer getPc() {return currentPage;}public void setPc(Integer pc) {this.currentPage = pc;}public Integer getTr() {return allNum;}public void setTr(Integer tr) {this.allNum = tr;}public Integer getPs() {return onePageNum;}public void setPs(Integer ps) {this.onePageNum = ps;}public Integer getTp() {//總頁數(shù)=總記錄數(shù)/頁大小int tp=allNum/onePageNum;return allNum%onePageNum==0?tp:tp+1;}public List<T> getBeanList() {return beanList;}public void setBeanList(List<T> beanList) {this.beanList = beanList;} }BookDao.java 實現(xiàn)圖書增刪改查、分頁
public interface BookDao {public int addBook(Book book);public int deleteBookByid(int id);public int updateBook(Book book);public List<Book> queryAllBook();public Book getBookById(int id);// 添加圖書圖片public int updateBookImg(Book book, int id);//查詢數(shù)據(jù)庫中總共有多少條數(shù)據(jù)public int countBook();/*** 查詢某一頁的記錄數(shù)(pc:當前頁碼 ps當前頁的數(shù)據(jù)條數(shù))*/public PageBean<Book> queryPageBook(int pc, int ps); }BookDaoImp.java?
import java.sql.Connection; import java.util.List;import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler;import com.demo.po.Book; import com.demo.po.PageBean; import com.demo.utils.DBUTils;public class BookDaoImpl implements BookDao {private Connection conn;private QueryRunner qr = new QueryRunner();/*** 添加圖書*/@Overridepublic int addBook(Book book) {// TODO Auto-generated method stubtry {conn = DBUTils.getConn();String sql = "insert into tb_book(bookName,bookAuthor,\r\n"+ "bookPrice,bookNum,bookDate) values(?,?,?,?,?)";int count = qr.update(conn, sql, book.getBookName(), book.getBookAuthor(), book.getBookPrice(),book.getBookNum(), book.getBookDate());return count;} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}return -1;}@Overridepublic int deleteBookByid(int id) {// TODO Auto-generated method stubtry {conn = DBUTils.getConn();String sql = "delete from tb_book where id=?";int count = qr.update(conn, sql, id);return count;} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}return -1;}@Overridepublic int updateBook(Book book) {// TODO Auto-generated method stubtry {conn = DBUTils.getConn();String sql = "update tb_book set bookName=?,bookAuthor=?," + "bookPrice=?,bookNum=?,bookDate=? where id=?";int count = qr.update(conn, sql, book.getBookName(), book.getBookAuthor(), book.getBookPrice(),book.getBookNum(), book.getBookDate(), book.getId());return count;} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}return -1;}@Overridepublic List<Book> queryAllBook() {// TODO Auto-generated method stubtry {conn = DBUTils.getConn();String sql = "select id,bookName,bookAuthor,bookPrice,bookNum,bookDate,path from tb_book";List<Book> books = qr.query(conn, sql, new BeanListHandler<Book>(Book.class));return books;} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}return null;}/*** 查詢單條數(shù)據(jù)*/@Overridepublic Book getBookById(int id) {// TODO Auto-generated method stubtry {conn = DBUTils.getConn();String sql = "select id,bookName,bookAuthor,bookPrice," + "bookNum,bookDate,path from tb_book where id=?";Book book = qr.query(conn, sql, new BeanHandler<Book>(Book.class), id);return book;} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}return null;}/*** 查詢總共有多少條數(shù)據(jù)*/@Overridepublic int countBook() {// TODO Auto-generated method stubtry {conn = DBUTils.getConn();String sql = "select count(1) from tb_book";Number cnt = qr.query(conn, sql, new ScalarHandler<Number>());return cnt.intValue();} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}return -1;}/** (pc:當前頁碼 ps當前頁的數(shù)據(jù)條數(shù)) private Integer pc;// 當前頁碼 private Integer tr;//總數(shù)據(jù)條數(shù)* private Integer ps;// 頁面大小(一頁的數(shù)據(jù)) private Integer tp;// 總頁數(shù) private List<T>* beanList;// 當前頁數(shù)據(jù)顯示 (non-Javadoc)* * @see com.demo.dao.BookDao#queryPageBook(int, int)*/@Overridepublic PageBean<Book> queryPageBook(int pc, int ps) {// TODO Auto-generated method stubtry {conn = DBUTils.getConn();PageBean<Book> pageBean = new PageBean();pageBean.setPc(pc);// 當前頁碼pageBean.setPs(ps);// 當前頁的數(shù)據(jù)條數(shù)pageBean.setTr(countBook());// 總數(shù)據(jù)條數(shù)// (pc-1)*ps:(當前頁-1)*當前頁數(shù)據(jù)條數(shù)String sql = "select * from tb_book limit " + (pc - 1) * ps + "," + ps;System.out.println("sql=" + sql);List<Book> books = qr.query(conn, sql, new BeanListHandler<Book>(Book.class));System.out.println("books==" + books);pageBean.setBeanList(books);return pageBean;} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}return null;}//添加圖書圖片@Overridepublic int updateBookImg(Book book, int id) {// TODO Auto-generated method stubtry {conn = DBUTils.getConn();String sql = "update tb_book set path=? where id=?";int count = qr.update(conn, sql, book.getPath(), id);return 0;} catch (Exception e) {// TODO: handle exceptione.printStackTrace();}return -1;} }BookService接口 實現(xiàn)增刪改查、分頁
public interface BookService { public int addBook(Book book); public int deleteBookById(int id); public int updateBook(Book book); public List<Book> queryAllBook();//查詢所有數(shù)據(jù) public Book getBookById(int id);//查詢一條數(shù)據(jù) //添加圖片 public int updateImg(Book book,int id); //查詢某一頁的記錄數(shù) public PageBean<Book> queryPageBook(int pc,int ps); }BookServiceImpl
public class BookServiceImpl implements BookService{ private BookDao bookDao=new BookDaoImpl();@Overridepublic int addBook(Book book) {// TODO Auto-generated method stubreturn bookDao.addBook(book);}@Overridepublic int deleteBookById(int id) {// TODO Auto-generated method stubreturn bookDao.deleteBookByid(id);}@Overridepublic int updateBook(Book book) {// TODO Auto-generated method stubreturn bookDao.updateBook(book);}@Overridepublic List<Book> queryAllBook() {// TODO Auto-generated method stubreturn bookDao.queryAllBook();}@Overridepublic Book getBookById(int id) {// TODO Auto-generated method stubreturn bookDao.getBookById(id);}@Overridepublic PageBean<Book> queryPageBook(int pc, int ps) {// TODO Auto-generated method stubreturn bookDao.queryPageBook(pc, ps);}@Overridepublic int updateImg(Book book, int id) {// TODO Auto-generated method stubreturn bookDao.updateBookImg(book, id);} }addbook.jsp添加和修改圖書界面
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>添加圖書</title> </head> <body><form action="../addbook.do">圖示名稱:<input type="text" name="bookname">圖書作者:<input type="text" name="bookauthor">圖書價格:<input type="text" name="bookprice">圖書數(shù)量:<input type="text" name="booknum"><input type="submit" name="添加圖書"></form> </body> </html>BookAddServlet.java 提交添加的圖書信息
private BookService bookService = new BookServiceImpl();//addbook.doprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stubString bookName = request.getParameter("bookname");String bookAuthor = request.getParameter("bookauthor");Float bookPrice = Float.parseFloat(request.getParameter("bookprice"));int bookNum = Integer.parseInt(request.getParameter("booknum"));Book book = new Book(bookName, bookAuthor, bookPrice, bookNum, new Date());int flag = bookService.addBook(book);if (flag > 0) {response.sendRedirect("query.do");} else {response.sendRedirect("addbook.jsp");}}booklist.jsp查詢圖書與分頁顯示界面
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><!DOCTYPE html> <html> <head> <meta charset="UTF-8"><script src="https://cdn.bootcss.com/jquery/2.2.4/jquery.min.js"></script> <title>顯示圖書</title> </head> <body><table border="1"><tr><td>序號</td><td>圖片</td><td>書名</td><td>作者</td><td>價格</td><td>數(shù)量</td><td>時間</td><td>修改</td><td>刪除</td></tr><c:forEach items="${pb.beanList }" var="book" varStatus="s"><tr><td>${s.count}</td><td><img width="60" height="60"src="../../0621crudorimg/images/${book.path}"></td></td><td>${book.bookName }</td><td>${book.bookAuthor }</td><td>${book.bookPrice }</td><td>${book.bookNum }</td><td>${book.bookDate}</td><td><a href="edit.do?id=${book.id}">修改</a></td><td><a href="delete.do?id=${book.id}">刪除</a></td><td><form action="aaa.do?id=${book.id}" method="post"enctype="multipart/form-data"><input type="file" name="images"><button type="submit" name="upload">上傳</button></form> </td></tr></c:forEach></table><table>第${pb.pc }頁/共${pb.tp}頁<a href="<c:url value='query.do?pc=1'/>">首頁</a><c:if test="${pb.pc>1 }"><a href="<c:url value='query.do?pc=${pb.pc-1}'/>">上一頁</a></c:if><c:if test="${pb.pc<pb.tp }"><a href="<c:url value='query.do?pc=${pb.pc+1}'/>">下一頁</a></c:if><a href="<c:url value='query.do?pc=${pb.tp}'/>">尾頁</a></table><!-- <form action="aaa.do" method="post" enctype="multipart/form-data"><input type="file" name="images"><button type="submit" name="upload">上傳</button></form> --> </body> </html>BookQueryAllServlet 查詢數(shù)據(jù)和分頁請求
public class BookQueryAllServlet extends HttpServlet {private static final long serialVersionUID = 1L;private BookService bookService = new BookServiceImpl();// query.doprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 查詢數(shù)據(jù)List<Book> books = bookService.queryAllBook();request.setAttribute("books", books);// 設(shè)置分頁int pc = getPc(request, response);int ps = 10; // 每頁的大小;PageBean<Book> pageBean = bookService.queryPageBook(pc, ps);request.setAttribute("pb", pageBean);request.getRequestDispatcher("jsp/booklist.jsp").forward(request, response);}protected int getPc(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stub// 如果當前頁傳的空,默認當前頁就是第一頁1String pc = request.getParameter("pc");if (pc == null || pc.trim().isEmpty()) {return 1;}return Integer.parseInt(pc);}}BookEditServlet 點擊修改時,獲取要修改的圖書id
public class BookEditServlet extends HttpServlet {private static final long serialVersionUID = 1L;//edit.do private BookService bookService=new BookServiceImpl();/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubint id=Integer.parseInt(request.getParameter("id"));Book book=bookService.getBookById(id);request.setAttribute("book", book);request.getRequestDispatcher("jsp/updatebook.jsp").forward(request, response); }}updatebook.jsp 修改界面 在頁面顯示原有圖書信息
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>更新圖書</title> </head> <body><form action="update.do"><input type="hidden" name="id" value="${book.id }">書名:<input type="text" name="bookname" value="${book.bookName }"><br>作者:<input type="text" name="bookauthor" value="${book.bookAuthor }"><br>價格:<input type="text" name="bookprice" value="${book.bookPrice }"><br>數(shù)量:<input type="text" name="booknum" value="${book.bookNum}"><br><input type="submit" value="修改"><br></form> </body> </html>BookUpdateServlet修改圖書
public class BookUpdateServlet extends HttpServlet {private static final long serialVersionUID = 1L;private BookService bookService = new BookServiceImpl();///update.doprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stubint id = Integer.parseInt(request.getParameter("id"));String bookName = request.getParameter("bookname");String bookAuthor = request.getParameter("bookauthor");float bookPrice = Float.parseFloat(request.getParameter("bookprice"));int bookNum = Integer.parseInt(request.getParameter("booknum"));System.out.println(id+bookName+bookAuthor+bookPrice+bookNum);Book book = new Book(bookName, bookAuthor, bookPrice, bookNum, new Date());book.setId(id);int count = bookService.updateBook(book);if (count > 0) {response.sendRedirect("query.do");}} }BookDeleteServlet刪除圖書
public class BookDeleteServlet extends HttpServlet {private static final long serialVersionUID = 1L;private BookService bookService = new BookServiceImpl();// delete.doprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stubint id = Integer.parseInt(request.getParameter("id"));int count = bookService.deleteBookById(id);if (count > 0) {response.sendRedirect("query.do");}} }TestBookManager測試類 添加圖書
public class TestBookManager {BookDao bookDao;@Beforepublic void init() {bookDao = new BookDaoImpl();}@Testpublic void testAddBook() {for (int i = 0; i < 1000; i++) {Book book = new Book("秦時明月第" + i+"集", "中國人" + i, 99.0f, 100, new Date());int count = bookDao.addBook(book);System.out.println("count=" + count);}} }?
總結(jié)
以上是生活随笔為你收集整理的实现图书增删改查和分页显示图书信息的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大数据应用分析解决方案----图书出版
- 下一篇: 【文末福利】用Python画了一幅《海上