Web图书管理系统---分页、上传、下载、增删改查

来源:互联网 发布:linux 查看进度 编辑:程序博客网 时间:2024/05/22 05:58

一:数据库设计




1.默认访问时分页显示出图书列表,进行隔行变色,并且对上一页和下一页进行限定

当前页数为1时,点击上一页给出提示”已经是第一页了,请点击下一页进行查看”

当前页数和总页数相等时,点击下一页给出提示“已经是最后一页了,请点击上一页进行查看”

如图一所示


2.可以根据图书名称和图书分类进行模糊查询,并且分页展示数据,进行隔行变色,并且对上一页和下一页进行限定,当前页数为1时,点击上一页给出提示”已经是第一页了,请点击下一页进行查看”,当前页数和总页数相等时,点击下一页给出提示“已经是最后一页了,请点击上一页进行查看”

连接数据库工具类:BaseDao

package cn.book.util;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;//数据库连接与关闭工具类public class BaseDao {public static final String driver = "com.mysql.jdbc.Driver";public static final String url = "jdbc:mysql://localhost:3306/bookmanager";public static final String username = "root";public static final String password = "";// 1.3 创建和数据库交互的三大对象protected Connection con; // 连接对象protected PreparedStatement ps;// 命令对象protected ResultSet rs; // 结果集对象(读取器对象)// 1.4 获取数据库连接对象public Connection getConnection() {try {Class.forName(driver);// 如果连接对象为空 ,或者连接被关闭,重新构建连接对象if (con == null || con.isClosed()) {con = DriverManager.getConnection(url, username, password);}} catch (ClassNotFoundException e) {e.printStackTrace();} catch (SQLException e) {e.printStackTrace();}return con;}// 1.5 释放数据库连接对象public void closeAll() {// 若结果集对象不为空,则关闭try {if (rs != null) {rs.close();}if (ps != null) {ps.close();}if (con != null) {con.close();}} catch (Exception ex) {ex.printStackTrace();}}// 1.6 写一个方法:执行增删改操作public int executeUpdate(String sql, Object... objs) throws Exception {con = getConnection();ps = con.prepareStatement(sql);for (int i = 0; i < objs.length; i++) {ps.setObject(i + 1, objs[i]);}int count = ps.executeUpdate();return count;}// 1.7 写一个方法 ,执行查询操作public ResultSet executeSelect(String sql, Object... prams) {con = getConnection();try {ps = con.prepareStatement(sql);for (int i = 0; i < prams.length; i++) {ps.setObject(i + 1, prams[i]);}rs = ps.executeQuery();} catch (SQLException e) {e.printStackTrace();} finally {}return rs;}}


图书接口:BookDao

/** *  * 图书接口 * */public interface BookDao {//查询图书列表(分页)public List<Book> selectbook(int pageIndex,int pageSize) throws Exception;//查询Book表的记录数public int getCount() throws Exception;//按图书名称查询(分页)public List<Book> likebook(int category,String name,int pageIndex, int pageSize) throws Exception;//查询Book表的记录数public int getselectCount(int category,String name) throws Exception;//删除bookpublic int deletebook(int id) throws Exception;//查询bookpublic Book uploadbook(int id) throws Exception;//查询book分类public List<BookCategory> selectcategory() throws Exception;//修改图书public int bookupdate(Book book,int id) throws Exception;//添加图书public int addbook(Book book) throws Exception;}

简单分页和多条件分页的方法:

// 查询图书列表(分页)@Overridepublic List<Book> selectbook(int pageIndex, int pageSize) throws Exception {// 创建list集合存放book对象List<Book> list = new ArrayList<Book>();String sql = "select * from book limit ?,?";Object[] obj = { pageIndex, pageSize };ResultSet rs = executeSelect(sql, obj);if (rs != null) {while (rs.next()) {// 创建book对象Book book = new Book();book.setBookid(rs.getInt("bookid"));book.setBookname(rs.getString("bookname"));book.setBookpicture(rs.getString("bookpicture"));book.setBookprice(rs.getDouble("bookprice"));book.setBookabout(rs.getString("bookabout"));book.setBookauthor(rs.getString("bookauthor"));book.setBookcategory(rs.getInt("bookcategory"));book.setBookdatatime(rs.getDate("bookdatetime"));list.add(book);}}return list;}// 查询book表中的记录数@Overridepublic int getCount() throws Exception {int result = 0;String sql = "select count(*) as num from book";ResultSet rs = executeSelect(sql);if (rs != null) {if (rs.next()) {result = rs.getInt("num");}closeAll();}return result;}// 按名称模糊查询(分页)@Overridepublic List<Book> likebook(int category, String name,int pageIndex, int pageSize)throws Exception {// 创建list集合存放book对象List<Book> list = new ArrayList<Book>();StringBuffer sb=new StringBuffer("select * from book where 1=1");if(category!=0){sb=sb.append(" and bookcategory='"+category+"' ");}if(name!=""){sb=sb.append(" and bookname like '%"+name+"%'");}sb=sb.append(" limit ?,?");Object[] obj = { pageIndex, pageSize };ResultSet rs = executeSelect(sb.toString(), obj);if (rs != null) {while (rs.next()) {// 创建book对象Book book = new Book();book.setBookid(rs.getInt("bookid"));book.setBookname(rs.getString("bookname"));book.setBookpicture(rs.getString("bookpicture"));book.setBookprice(rs.getDouble("bookprice"));book.setBookabout(rs.getString("bookabout"));book.setBookauthor(rs.getString("bookauthor"));book.setBookcategory(rs.getInt("bookcategory"));book.setBookdatatime(rs.getDate("bookdatetime"));list.add(book);}}return list;}@Overridepublic int getselectCount(int category,String name) throws Exception {int result = 0;StringBuffer sb=new StringBuffer("select count(*) as num from book where 1=1 ");if(category!=0){sb=sb.append(" and bookcategory='"+category+"' ");}if(name!=""){sb=sb.append(" and bookname like '%"+name+"%'");}ResultSet rs = executeSelect(sb.toString());if (rs != null) {if (rs.next()) {result = rs.getInt("num");}closeAll();}return result;}


查询图书分类的方法:

public List<BookCategory> selectcategory() throws Exception {List<BookCategory> list=new ArrayList<BookCategory>();String sql="select * from BookCategory";ResultSet rs = executeSelect(sql);if(rs!=null){while(rs.next()){BookCategory cate=new BookCategory();cate.setCateid(rs.getInt("cateid"));cate.setCatename(rs.getString("catename"));list.add(cate);}}return list;}


BookServlet代码如下:

request.setCharacterEncoding("UTF-8");response.setCharacterEncoding("UTF-8");response.setContentType("text/html;charset=UTF-8");response.setHeader("content-type", "text/html;charset=UTF-8");// 创建Service对象BookService service = new BookServiceImpl();try {List<BookCategory> catelists = service.selectcategory();request.setAttribute("catelists", catelists);} catch (Exception e1) {e1.printStackTrace();}String action = request.getParameter("action");Page pages = new Page();// 默认显示三条数据int pageSize = 3;pages.setPageSize(pageSize);// 当前页int myIndex;String pageIndex = request.getParameter("pageIndex");if (pageIndex != null) {myIndex = Integer.parseInt(pageIndex);} else {myIndex = 1;}pages.setPageIndex(myIndex);String select=request.getParameter("select");if(select!=null&&select!=""){System.out.println("=====================");String selectname = request.getParameter("selectname");String selectcate=request.getParameter("bookcategoryid");int mytotal;try {int totalpage = service.getselectCount(Integer.parseInt(selectcate), selectname);if (totalpage % pageSize == 0) {mytotal = totalpage / pageSize;} else {mytotal = totalpage / pageSize + 1;}pages.setTotalPages(mytotal);List<Book> likebook = service.likebook(Integer.parseInt(selectcate), selectname,(pages.getPageIndex() - 1)* pages.getPageSize(), pages.getPageSize());pages.setBooklist(likebook);request.setAttribute("selectname", selectname);request.setAttribute("selectcate", selectcate);request.setAttribute("Page", pages);} catch (Exception e) {}}else{int mytotal;try {int totalpage = service.getCount();if (totalpage % pageSize == 0) {mytotal = totalpage / pageSize;} else {mytotal = totalpage / pageSize + 1;}pages.setTotalPages(mytotal);List<Book> list = service.selectbook((pages.getPageIndex() - 1)* pages.getPageSize(), pages.getPageSize());pages.setBooklist(list);request.setAttribute("Page", pages);} catch (Exception e) {}}
booklist.jsp页面---------显示图示列表

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><script type="text/javascript" src="<%=path%>/js/jquery-1.8.3.min.js"></script><script type="text/javascript">$(function() {$("#centerB tr:odd").css("background", "#AAAAAA");});function up() {alert("已经是第一页了,请点击下一页查看!");}function down() {alert("已经是最后一页了,请点击上一页查看!");}function deletebook() {var result = confirm('确定删除?');if (result) {alert("删除成功!");}}function addbook() {location.href="/BookManager/BookServlet?action=selectbookcatefory";}function nextPage(pageIndex){    document.form1.action="<%=path%>/BookServlet?select=1&pageIndex="+pageIndex;    document.form1.submit();}function upPage(pageIndex){    document.form1.action="<%=path%>/BookServlet?select=1&pageIndex="+pageIndex;    document.form1.submit();}</script><style>li {list-style: none;float: left;}a {text-decoration: none;}</style><title>图书管理系统</title></head><body><div align="center"><h2 style="color: blue">图书管理系统</h2><div><form name="form1" action="<%=path %>/BookServlet?select=1" method="post">   <input type="text" placeholder="请按图书名称查询" name="selectname" value="${selectname }"/><select name="bookcategoryid"><option value="0">请选择分类</option><c:if test="${catelists !=null }"><c:forEach var="item" items="${catelists }"><option value="${item.cateid}" <c:if test="${item.cateid==selectcate }">selected="selected"</c:if>>${item.catename}</option></c:forEach></c:if></select> <input type="submit"value="点击查询"/><input type="button" value="添加图书" onclick="addbook();"/></form><table border="1px;" id="centerB"><tr style="background-color: yellow"><th align="center">图书编号</th><th align="center">图书图片</th><th align="center">图书名称</th><th align="center">图书作者</th><th align="center">图书分类</th><th align="center">图书价格</th><th align="center">发布时间</th><th align="center">操作</th></tr><c:forEach var="item" items="${Page.booklist }"><tr><td align="center" id="bookids">${item.bookid}</td><td align="center"><imgsrc="<%=path%>/image/${item.bookpicture}"style="width: 100px;height: 100px;" /></td><td align="center">${item.bookname }</td><td align="center">${item.bookauthor}</td><c:if test="${item.bookcategory eq 1}"><td align="center">名家作品</td></c:if><c:if test="${item.bookcategory eq 2}"><td align="center">中国文学</td></c:if><c:if test="${item.bookcategory eq 3}"><td align="center">四大名著</td></c:if><c:if test="${item.bookcategory eq 4}"><td align="center">科幻小说</td></c:if><td align="center">${item.bookprice}</td><td align="center" id="time">${item.bookdatatime}</td><td align="center"> <a href="<%=path%>/BookServlet?action=uploadbook&bookid=${item.bookid}">修改</a>  <a href="<%=path %>/BookServlet?action=deletebook&bookid=${item.bookid}" onclick="deletebook()">删除</a></td></tr></c:forEach></table><hr /><div style="padding-left: 618px;"><ul>    <li>当前页数:[${Page.pageIndex} / ${Page.totalPages}]   </li><li><a href="<%=path%>/BookServlet?pageIndex=1">首页</a>   </li><c:if test="${Page.totalPages==1}"><li><a onclick="up();">上一页</a>   </li><li><a onclick="down();">下一页</a>   </li></c:if><c:if test="${Page.pageIndex < Page.totalPages && Page.pageIndex==1}"><li><a onclick="up();">上一页</a>   </li><li><a href="javascript:nextPage(${Page.pageIndex+1 })">下一页</a>   </li></c:if><c:if test="${Page.pageIndex < Page.totalPages && Page.pageIndex!=1}"><li><a  href="<%=path%>/BookServlet?pageIndex=${Page.pageIndex-1}">上一页</a>   </li><li><a href="<%=path%>/BookServlet?pageIndex=${Page.pageIndex+1}">下一页</a>   </li></c:if><c:if test="${Page.pageIndex >= Page.totalPages && Page.pageIndex>1}"><li><a  href="javascript:upPage(${Page.pageIndex-1 })">上一页</a>   </li><li><a  onclick="down();">下一页</a>   </li></c:if><li><ahref="<%=path%>/BookServlet?pageIndex=${Page.totalPages}">尾页</a>   </li></ul></div></div></div></body></html>

3.添加图书,文件上传,进行表单验证,当添加成功时,提示“添加成功!”,返回列表页面,当点击取消时提示“确定取消吗?”,当点击确定时返回列表,点击取消则回到当前页面,如图三所示:



if (action.equals("insertbook")) {Book book = new Book();PrintWriter writer = response.getWriter();String filedname = "";boolean flag = ServletFileUpload.isMultipartContent(request);if (flag) {DiskFileItemFactory factory = new DiskFileItemFactory();ServletFileUpload upload = new ServletFileUpload(factory);try {List<FileItem> item = upload.parseRequest(request);Iterator<FileItem> items = item.iterator();while (items.hasNext()) {FileItem fileitem = (FileItem) items.next();if (fileitem.isFormField()) {filedname = fileitem.getFieldName();if (filedname.equals("bookName")) {book.setBookname(fileitem.getString("UTF-8"));} else if (filedname.equals("bookauthor")) {book.setBookauthor(fileitem.getString("UTF-8"));} else if (filedname.equals("bookcategoryid")) {book.setBookcategory(Integer.parseInt(fileitem.getString("UTF-8")));} else if (filedname.equals("bookPrice")) {book.setBookprice(Float.parseFloat(fileitem.getString("UTF-8")));} else if (filedname.equals("bookdatetime")) {String time = fileitem.getString("UTF-8");SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");Date date;try {date = simpleDateFormat.parse(time);book.setBookdatatime(date);} catch (ParseException e) {e.printStackTrace();}} else if (filedname.equals("bookabout")) {book.setBookabout(fileitem.getString("UTF-8"));}} else {String tomactPath = this.getServletContext().getRealPath("/image/");String fileName1 = fileitem.getName();System.out.println(fileName1);book.setBookpicture(fileName1);if (fileName1 != null && !fileName1.equals("")) {File fullFile = new File(fileitem.getName());File saveFile = new File(tomactPath,fullFile.getName());try {fileitem.write(saveFile);} catch (Exception e) {e.printStackTrace();}tomactPath = fullFile.getName();System.out.println("上传成功");}}}} catch (FileUploadException e) {e.printStackTrace();}}try {int addbook = service.addbook(book);if (addbook > 0) {response.sendRedirect("/BookManager/BookServlet");} else {response.sendRedirect("BookManager/BookServlet?action=selectbookcatefory");}} catch (Exception e) {e.printStackTrace();}}
bookadd.jsp页面------------添加图示页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><script type="text/javascript" src="<%=path%>/js/jquery-1.8.3.min.js"></script><script type="text/javascript">function out() {var result = confirm('确定取消吗?');if (result) {location.href = "/BookManager/BookServlet";}}function check() { var flag=true;    if($("[name=bookName]").val()==""){    alert("请输入图书名称");return false;}if($("[name=bookauthor]").val()==""){    alert("请输入图书作者");return false;}if($("[name=bookPrice]").val()!=""&&!/^(d*.d{0,2}|d+).*$/i.test($("[name=bookPrice]").val())){    alert("图书价格格式不准确!");return false;}if($("[name=bookPrice]").val()==""){    alert("请输入图书价格");return false;}if($("[name=bookdatetime]").val()==""){    alert("请输入图书发布时间");return false;}if($("[name=bookabout]").val()==""){    alert("请输入图书描述");return false;}if($("[name=filename]").val()==""){    alert("请选择图书照片");return false;}if(flag==true){alert("添加成功");}return flag;}</script><title>添加图书</title></head><body><div align="center"><h2 style="color: blue">添加图书</h2><form action="<%=path%>/BookServlet?action=insertbook"method="post" enctype="multipart/form-data" onsubmit="return check()"><table class="form" style="border: 1px;"><tr><td class="field">图书名称:</td><td><input type="text" class="text" name="bookName" /></td></tr><tr><td class="field">图书作者:</td><td><input type="text" class="text" name="bookauthor" /></td></tr><tr><td>图书分类:</td><td><select name="bookcategoryid"><c:forEach var="item" items="${catelist }"><option value="${item.cateid }">${item.catename }</option></c:forEach></select></td></tr><tr><td class="field">图书价格:</td><td><input type="text" class="text tiny" name="bookPrice"value="" />/元</td></tr><tr><td class="field">发布时间:</td><td><input type="date" class="text tiny" name="bookdatetime"value="" /></td></tr><tr><td class="field">图书描述:</td><td><textarea rows="" cols=""style="width: 178px;height: 200px;" name="bookabout"></textarea></td></tr><tr><td class="field">图书图片:</td><td><input type="file" class="text" name="filename" /></td></tr><tr align="center"><td align="center"><inputtype="submit" value="添加" /></td><td align="center"><label class="ui-blue"><inputtype="button" onclick="out();" value="取消" /></label></td></tr></table></form></div></body></html>


在首页点击“添加图书”按钮Servlet的代码:


if (action.equals("selectbookcatefory")) {try {List<BookCategory> catelist = service.selectcategory();request.setAttribute("catelist", catelist);request.getRequestDispatcher("/jsp/bookadd.jsp").forward(request, response);} catch (Exception e) {e.printStackTrace();}


4.修改图书:点击修改图书时,将图书信息查询出来,并且展示到修改图书的页面,当不选择上传图书图片时,默认选择当前的图书图片,当点击下载文件时,可以进行图书图片的下载,点击确定按钮时,进行表单验证,当信息无误后提示“修改成功!”跳转到列表页面,当点击取消时提示“确定取消吗?”,当点击确定时返回列表,点击取消则回到当前页面,如图四所示:


修改图书、添加图书和根据图书id获得对象的方法:

@Overridepublic Book uploadbook(int id) throws Exception {Book book=new Book();String sql="select * from book where bookid='"+id+"'";ResultSet rs = executeSelect(sql);if(rs!=null){if(rs.next()){book.setBookabout(rs.getString("bookabout"));book.setBookauthor(rs.getString("bookauthor"));book.setBookcategory(rs.getInt("bookcategory"));book.setBookdatatime(rs.getDate("bookdatetime"));book.setBookid(rs.getInt("bookid"));book.setBookname(rs.getString("bookname"));book.setBookpicture(rs.getString("bookpicture"));book.setBookprice(rs.getDouble("bookprice"));}}return book;}//修改图书@Overridepublic int bookupdate(Book book,int id) throws Exception {String sql="update book set bookname=?,bookcategory=?,bookprice=?,bookauthor=?,bookabout=?,bookdatetime=?,bookpicture=? where bookid=?";Object[] obj={book.getBookname(),book.getBookcategory(),book.getBookprice(),book.getBookauthor(),book.getBookabout(),book.getBookdatatime(),book.getBookpicture(),id};int count = executeUpdate(sql, obj);return count;}//添加图书@Overridepublic int addbook(Book book) throws Exception {String sql="insert into book(bookname,bookcategory,bookprice,bookauthor,bookabout,bookdatetime,bookpicture) values(?,?,?,?,?,?,?)";Object [] obj={book.getBookname(),book.getBookcategory(),book.getBookprice(),book.getBookauthor(),book.getBookabout(),book.getBookdatatime(),book.getBookpicture()};int count = executeUpdate(sql, obj);return count;}



BookServlet代码

//编辑图书信息传到图书修改页面} else if (action.equals("uploadbook")) {String bookid = request.getParameter("bookid");try {List<BookCategory> catelist = service.selectcategory();Book book = service.uploadbook(Integer.parseInt(bookid));request.setAttribute("Book", book);request.setAttribute("catelist", catelist);request.getRequestDispatcher("/jsp/bookupdate.jsp").forward(request, response);} catch (NumberFormatException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}// 修改图书} else if (action.equals("updatebook")) {String id = request.getParameter("id");int bookid = Integer.parseInt(id);Book book = new Book();PrintWriter writer = response.getWriter();String filedname = "";boolean flag = ServletFileUpload.isMultipartContent(request);if (flag) {DiskFileItemFactory factory = new DiskFileItemFactory();ServletFileUpload upload = new ServletFileUpload(factory);try {List<FileItem> item = upload.parseRequest(request);Iterator<FileItem> items = item.iterator();while (items.hasNext()) {FileItem fileitem = (FileItem) items.next();if (fileitem.isFormField()) {filedname = fileitem.getFieldName();if (filedname.equals("bookName")) {book.setBookname(fileitem.getString("UTF-8"));} else if (filedname.equals("bookauthor")) {book.setBookauthor(fileitem.getString("UTF-8"));} else if (filedname.equals("bookcategoryid")) {book.setBookcategory(Integer.parseInt(fileitem.getString("UTF-8")));} else if (filedname.equals("bookPrice")) {book.setBookprice(Float.parseFloat(fileitem.getString("UTF-8")));} else if (filedname.equals("bookdatetime")) {String time = fileitem.getString("UTF-8");SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");Date date;try {date = simpleDateFormat.parse(time);book.setBookdatatime(date);} catch (ParseException e) {e.printStackTrace();}} else if (filedname.equals("bookabout")) {book.setBookabout(fileitem.getString("UTF-8"));}} else {String tomactPath = this.getServletContext().getRealPath("/image/");String fileName1 = fileitem.getName();if (fileName1 == "") {Book books = service.uploadbook(bookid);book.setBookpicture(books.getBookpicture());} else {book.setBookpicture(fileName1);}if (fileName1 != null && !fileName1.equals("")) {File fullFile = new File(fileitem.getName());File saveFile = new File(tomactPath,fullFile.getName());try {fileitem.write(saveFile);} catch (Exception e) {e.printStackTrace();}tomactPath = fullFile.getName();System.out.println("上传成功");}}}} catch (FileUploadException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}try {int addbook = service.bookupdate(book, bookid);if (addbook > 0) {response.sendRedirect("/BookManager/BookServlet");} else {response.sendRedirect("BookManager/BookServlet?action=uploadbook");}} catch (Exception e) {e.printStackTrace();}}

bookupdate.jsp-----------图书修改页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ path + "/";%><%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><script type="text/javascript" src="<%=path%>/js/jquery-1.8.3.min.js"></script><script type="text/javascript">function out() {var result = confirm('确定取消更改吗?');if (result) {location.href = "/BookManager/BookServlet";}}function OK() {alert("修改成功");}</script><title>修改图书</title></head><body><div align="center"><h2 style="color: blue">修改图书</h2><formaction="<%=path %>/BookServlet?action=updatebook&id=${Book.bookid}"method="post" enctype="multipart/form-data"><table class="form" style="border: 1px;"><tr><td class="field">图书名称:</td><td><input type="text" class="text" name="bookName"value="${Book.bookname }" /></td></tr><tr><td class="field">图书作者:</td><td><input type="text" class="text" name="bookauthor"value="${Book.bookauthor }" /></td></tr><tr><td>图书分类:</td><td><select name="bookcategoryid"><c:forEach var="item" items="${catelist }"><c:choose><c:when test="${item.cateid eq Book.bookcategory}"><option value="${item.cateid}" selected="selected">${item.catename}</option></c:when><c:otherwise><option value="${item.cateid }">${item.catename}</option></c:otherwise></c:choose></c:forEach></select></td></tr><tr><td class="field">图书价格:</td><td><input type="text" class="text tiny" name="bookPrice"value="${Book.bookprice }" />/元</td></tr><tr><td class="field">发布时间:</td><td><input type="date" class="text tiny" name="bookdatetime"value="${Book.bookdatatime }" /></td></tr><tr><td class="field">图书描述:</td><td><textarea rows="" cols=""style="width: 178px;height: 200px;" name="bookabout">${Book.bookabout }</textarea></td></tr><tr><td class="field">图书图片:</td><td><img src="image/${Book.bookpicture }"style="width: 100px; height: 100px;" name="fileimg"/><input type="file"class="text" name="bookpicture" value="" /><a href="<%=path%>/BookServlet?action=filedown&filename=${Book.bookpicture }">下载文件</a>  ${errorResult} </td></tr><tr align="center"><td align="center"><inputtype="submit" value="确定" onclick="OK();" /></td><td align="center"><label class="ui-blue"><inputtype="button" onclick="out();" value="取消" /></label></td></tr></table></form></div></body></html>

文件下载的 代码:

if(action.equals("filedown")){//文件下载的根路径String  path=getServletContext().getRealPath("/")+"image/";//取到要下载的文件名称String filename=request.getParameter("filename");//读取文件File  file=new File(path+filename);//判断file是否为nullif(file!=null){//设置相应的类型//setContentType  使客户端浏览器调用不同的模块处理相应的数据//文件下载所用的类型  application/x-msdownload或application/octet-streamresponse.setContentType("application/x-msdownload");//设置头信息  以复健的形式打开我们的下载文件  下载的时候文件名=filenameresponse.setHeader("Content-Disposition","attachment;filename=\""+filename+"\"");//读取我们需要下载的文件//获取文件输入流InputStream   inputStream=new FileInputStream(file);//获取文件返回的输出流ServletOutputStream  sops=response.getOutputStream();//循环将输入流信息写入到输出流中//定义一个变量Byte[]  每次读取1024个字节byte b[] =new byte[1024];int n;while((n=inputStream.read(b))!=-1){//如果不等于-1  循环读取//写入到输出流中sops.write(b, 0, n);}//关闭流  释放资源sops.close();inputStream.close();}}}

5.删除图书:点击删除按钮时,提示“确认删除吗?”,当点击确定时执行删除,点击取消时回到当前页面

删除的方法:

@Overridepublic int deletebook(int id) throws Exception {String sql="delete from book where bookid='"+id+"'";int count = executeUpdate(sql);return count;}


BookServlet代码:

if (action.equals("deletebook")) {String id = request.getParameter("bookid");try {int deletebook = service.deletebook(Integer.parseInt(id));if (deletebook > 0) {System.out.println("删除成功!");response.sendRedirect("/BookManager/BookServlet");} else {System.out.println("删除失败!");}} catch (NumberFormatException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}





阅读全文
0 0
原创粉丝点击