在图书更新时出现异常
问题描述:
之前根据老师的指导在删除和更新出现问题,删除已经解决了,然后在修改还是出现问题
相关代码:
ManagementController.java
package com.pre.library.controller;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.pre.library.entity.Books;
import com.pre.library.entity.Category;
import com.pre.library.service.BookService;
import com.pre.library.service.CategoryService;
/**
* Servlet implementation class ManagementController
*/
@WebServlet("/management")
public class ManagementController extends HttpServlet {
private static final long serialVersionUID = 1L;
private BookService bookService=new BookService();
private CategoryService categoryService=new CategoryService();
/**
* @see HttpServlet#HttpServlet()
*/
public ManagementController() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String method = request.getParameter("method");
if ("bookList".equals(method)) {
this.bookList(request, response);
}else if ("show_addBook".equals(method)) {
this.addBook(request, response);
}else if ("createBook".equals(method)) {
this.createBook(request, response);
}else if("deleteBook".equals(method)) {
this.deleteBook(request, response);
}else if(method.equals("show_updateBook")) {
this.showUpdatePage(request,response);
}else if(method.equals("update")) {
this.update(request,response);
}else if("categoryList".equals(method)) {
this.categoryList(request, response);
}else if("show_Category".equals(method)) {
this.addCategory(request,response);
}else if("categoryCreate".equals(method)) {
this.categoryCreate(request,response);
}
}
//category展示
public void categoryList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Category> categoryList=categoryService.categoryList();
request.setAttribute("categoryList", categoryList);
request.getRequestDispatcher("/WEB-INF/jsp/categoryList.jsp").forward(request, response);
}
//图书展示
private void bookList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Books> bookList = bookService.bookList();
request.setAttribute("bookList", bookList);
request.getRequestDispatcher("/WEB-INF/jsp/bookList.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
//显示新增页面
private void addBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/jsp/addBook.jsp").forward(request, response);
}
//显示新增分类页面
private void addCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/jsp/addCategory.jsp").forward(request, response);
}
//新增图书分类
private void categoryCreate(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 初始化FileUpload组件
FileItemFactory factory = new DiskFileItemFactory();
/**
* FileItemFactory 用于将前端表单的数据转换为一个个FileItem对象
* ServletFileUpload 则是为FileUpload组件提供Java web的Http请求解析
*/
ServletFileUpload sf = new ServletFileUpload(factory);
//2.遍历所有FileItem
try {
List<FileItem>formData=sf.parseRequest(request);
Category category=new Category();
for(FileItem fi:formData) {
if(fi.isFormField()) {
System.out.println("普通输入项:" + fi.getFieldName() + ":" + fi.getString("UTF-8"));
switch (fi.getFieldName()) {
case "categoryId":
category.setCategoryId(Integer.parseInt(fi.getString("UTF-8")));
break;
case "categoryName":
category.setCategoryName(fi.getString("UTF-8"));
break;
default:
break;
}
}else {
System.out.println("文件上传项:" + fi.getFieldName());
}
}
categoryService.addCategory(category);
response.sendRedirect("/management?method=categoryList");//返回列表页
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//新增图书信息
private void createBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1. 初始化FileUpload组件
FileItemFactory factory = new DiskFileItemFactory();
/**
* FileItemFactory 用于将前端表单的数据转换为一个个FileItem对象
* ServletFileUpload 则是为FileUpload组件提供Java web的Http请求解析
*/
ServletFileUpload sf = new ServletFileUpload(factory);
//2.遍历所有FileItem
try {
List<FileItem>formData=sf.parseRequest(request);
Books book=new Books();
for(FileItem fi:formData) {
if(fi.isFormField()) {
System.out.println("普通输入项:" + fi.getFieldName() + ":" + fi.getString("UTF-8"));
switch (fi.getFieldName()) {
case "bookId":
book.setBookId(Integer.parseInt(fi.getString("UTF-8")));
break;
case "bookName":
book.setBookName(fi.getString("UTF-8"));
break;
case "categoryId":
book.setCategoryId(fi.getString("UTF-8"));
break;
case "bookPrice":
book.setBookPrice(Integer.parseInt(fi.getString("UTF-8")));
break;
case "remarks":
book.setRemarks(fi.getString("UTF-8"));
break;
default:
break;
}
}else {
System.out.println("文件上传项:" + fi.getFieldName());
//3.文件保存到服务器目录
String path = request.getServletContext().getRealPath("/upload");
System.out.println("上传文件目录:" + path);
//String fileName = "test.jpg";
String fileName = UUID.randomUUID().toString();
//fi.getName()得到原始文件名,截取最后一个.后所有字符串,例如:wxml.jpg->.jpg
String suffix = fi.getName().substring(fi.getName().lastIndexOf("."));
//fi.write()写入目标文件
fi.write(new File(path,fileName + suffix));
book.setBookPic("/upload/" + fileName + suffix);
}
}
bookService.addBook(book);
response.sendRedirect("/management?method=bookList");//返回列表页
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 显示更新页面
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
private void showUpdatePage(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
Books book = bookService.findById(Integer.parseInt(id));
request.setAttribute("book", book);
request.getRequestDispatcher("/WEB-INF/jsp/updateBook.jsp").forward(request, response);
}
/**
* 实现油画更新
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
private void update(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
int isPreviewModified = 0;
//文件上传时的数据处理与标准表单完全不同
/*
String pname = request.getParameter("pname");
System.out.println(pname);
*/
//1. 初始化FileUpload组件
FileItemFactory factory = new DiskFileItemFactory();
/**
* FileItemFactory 用于将前端表单的数据转换为一个个FileItem对象
* ServletFileUpload 则是为FileUpload组件提供Java web的Http请求解析
*/
ServletFileUpload sf = new ServletFileUpload(factory);
//2. 遍历所有FileItem
try {
List<FileItem> formData = sf.parseRequest(request);
Books book = new Books();
for(FileItem fi:formData) {
if(fi.isFormField()) {
System.out.println("普通输入项:" + fi.getFieldName() + ":" + fi.getString("UTF-8"));
switch (fi.getFieldName()) {
case "bookId":
book.setBookId(Integer.parseInt(fi.getString("UTF-8")));
break;
case "bookName":
book.setBookName(fi.getString("UTF-8"));
break;
case "categoryId":
book.setCategoryId(fi.getString("UTF-8"));
break;
case "bookPrice":
book.setBookPrice(Integer.parseInt(fi.getString("UTF-8")));
break;
case "remaraks":
book.setRemarks(fi.getString("UTF-8"));
break;
case "isPreviewModified":
isPreviewModified = Integer.parseInt(fi.getString("UTF-8"));
break;
default:
break;
}
}else {
if(isPreviewModified == 1) {
System.out.println("文件上传项:" + fi.getFieldName());
//3.文件保存到服务器目录
String path = request.getServletContext().getRealPath("/upload");
System.out.println("上传文件目录:" + path);
//String fileName = "test.jpg";
String fileName = UUID.randomUUID().toString();
//fi.getName()得到原始文件名,截取最后一个.后所有字符串,例如:wxml.jpg->.jpg
String suffix = fi.getName().substring(fi.getName().lastIndexOf("."));
//fi.write()写入目标文件
fi.write(new File(path,fileName + suffix));
book.setBookPic("/upload/" + fileName + suffix);
}
}
}
//更新数据的核心方法
bookService.update(book,isPreviewModified);
response.sendRedirect("/management?method=bookList");//返回列表页
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//删除
public void deleteBook(HttpServletRequest request, HttpServletResponse response) throws IOException {
String id = request.getParameter("id");
System.out.println("id"+id);
PrintWriter out = response.getWriter();
try {
bookService.deleteBook(Integer.parseInt(id));
//{"result":"ok"}
out.println("{\"result\":\"ok\"}");
}catch(Exception e) {
e.printStackTrace();
out.println("{\"result\":\"" + e.getMessage() + "\"}");
}
}
}
Books.java:
package com.pre.library.entity;
/**
* 1.类型描述:图书id,图书名,图书分类,价格,图书封面,备注
* @author zhanzhimin
*
*/
public class Books {
private Integer id;//序号
private Integer bookId;//图书id
private String bookName;//图书名
private String categoryId;//图书分类分类1-计算机2-软件工程
private Integer bookPrice;//价格
private String bookPic;//图书封面
private String remarks;//备注
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id=id;
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public Integer getBookPrice() {
return bookPrice;
}
public void setBookPrice(Integer bookPrice) {
this.bookPrice = bookPrice;
}
public String getBookPic() {
return bookPic;
}
public void setBookPic(String bookPic) {
this.bookPic = bookPic;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
}
BookDao.java:
package com.pre.library.dao;
import java.util.List;
import com.pre.library.entity.Books;
import com.pre.library.utils.XmlDataSource;
public class BookDao {
//图书信息的展示,通过XmlDataSource文件进行读取
public List<Books> bookList() {
List<Books> bookList = XmlDataSource.bookData();
return bookList;
}
//查找
public Books findById(Integer id) {
List<Books> data = XmlDataSource.bookData();
Books book = null;
for(Books books : data) {
if(books.getId() == id) {
book = books;
break;
}
}
return book;
}
//图书添加
public void addBook(Books book) {
XmlDataSource.appendBook(book);
}
//删除图书
public void deleteBook(Integer id) {
XmlDataSource.deleteBook(id);
}
//更新图书
public void update(Books book) {
XmlDataSource.update(book);
}
}
BookService.java:
package com.pre.library.service;
import java.util.List;
import com.pre.library.dao.BookDao;
import com.pre.library.entity.Books;
public class BookService {
private BookDao bookDao=new BookDao();
//图书的展示
public List<Books> bookList() {
/*List<Books> bookList = XmlDataSource.bookData();
return bookList;*/
return bookDao.bookList();
}
//查询
public Books findById(Integer id) {
Books book = bookDao.findById(id);
if(book==null) {
throw new RuntimeException("[id=" + id +"]图书不存在");
}
return book;
}
//图书添加
public void addBook(Books book) {
bookDao.addBook(book);
}
//删除图书
public void deleteBook(Integer id) {
bookDao.deleteBook(id);
}
/**
* 更新业务逻辑
* @param newBook 新的图书数据
* @param isPreviewModified 是否修改bookPic属性
*/
public void update(Books newBook,Integer isPreviewModified) {
Books oldBook=this.findById(newBook.getId());
oldBook.setBookId(newBook.getBookId());
oldBook.setBookName(newBook.getBookName());
oldBook.setBookPrice(newBook.getBookPrice());
oldBook.setRemarks(newBook.getRemarks());
if(isPreviewModified==1) {
oldBook.setBookPic(newBook.getBookPic());
}
bookDao.update(oldBook);
}
public static void main(String[] arge) {
BookService bookService=new BookService();
List<Books> booklist=bookService.bookList();
for(Books books:booklist) {
System.out.println(books.getBookName());
}
}
}
XmlDataSource.java:
package com.pre.library.utils;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import com.pre.library.entity.Books;
import com.pre.library.entity.Category;
/**
* 数据源类,用于XML文件解析为Java对象
*
* @author zhanzhimin
*/
public class XmlDataSource {
private static List<Books> data = new ArrayList<Books>();
private static List<Category> categoryData=new ArrayList<Category>();
private static String dataFile;
private static String categoryDataFile;
static {
// painting.xml文件完整物理地址
// c:\new style\book.xml
// c:\new%20style\book.xml
dataFile = XmlDataSource.class.getResource("/book.xml").getPath();
categoryDataFile=XmlDataSource.class.getResource("/category.xml").getPath();
reloadBooks();
reloadCategory();
}
//对category进行编写
public static void reloadCategory() {
// 通过URLDecoder类将Base64转换成普通字符窜
URLDecoder decoder = new URLDecoder();
try {
categoryDataFile=decoder.decode(categoryDataFile,"utf-8");
System.out.println(categoryDataFile);
//利用dom4j进行解析
SAXReader reader=new SAXReader();
Document doucument=reader.read(categoryDataFile);
List<Node> list=doucument.selectNodes("/root/category");
categoryData.clear();
for(Node node:list) {
Element element=(Element)node;
String categoryId=element.elementText("categoryId");
String categoryName=element.elementText("categoryName");
Category category=new Category();
category.setCategoryId(Integer.parseInt(categoryId));
category.setCategoryName(categoryName);
categoryData.add(category);
System.out.println(categoryId+" "+categoryName);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//对book公共读取的方法
public static void reloadBooks() {
// 通过URLDecoder类将Base64转换成普通字符窜
URLDecoder decoder = new URLDecoder();
try {
dataFile = decoder.decode(dataFile, "utf-8");
System.out.println(dataFile);
// 利用dom4j对xml解析
SAXReader reader = new SAXReader();
Document document = reader.read(dataFile);
List<Node> list = document.selectNodes("/root/book");
//清空集合的数据
data.clear();
for (Node node : list) {
Element element = (Element) node;
String id = element.attributeValue("id");
String bookId = element.elementText("bookId");
String bookName = element.elementText("bookName");
Books book = new Books();
book.setId(Integer.parseInt(id));
book.setBookId(Integer.parseInt(bookId));
book.setBookName(bookName);
book.setCategoryId(element.elementText("categoryId"));
book.setBookPrice(Integer.parseInt(element.elementText("bookPrice")));
book.setBookPic(element.elementText("bookPic"));
book.setRemarks(element.elementText("remarks"));
data.add(book);
System.out.println(bookId + ":" + bookName);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//对category增加
public static void appendCategory(Category category) {
//利用SAXReader读取xml文档
SAXReader reader=new SAXReader();
Writer writer=null;
try {
Document document=reader.read(categoryDataFile);
Element root=document.getRootElement();
Element c=root.addElement("category");
//3.创建各个节点
c.addElement("categoryId").setText(category.getCategoryId().toString());
c.addElement("categoryName").setText(category.getCategoryName().toString());
//4.完成追加,写入xml
writer=new OutputStreamWriter(new FileOutputStream(categoryDataFile),"UTF-8");
document.write(writer);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(writer!=null) {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
reloadCategory();
}
}
/**
* 添加图书的信息
* @param 实体对象Books book
*
*/
public static void appendBook(Books book) {
//通过SAXReader读取xml文档,得到Document
SAXReader reader=new SAXReader();
Writer writer=null;
try {
Document document=reader.read(dataFile);
//2.创建book.xml的book节点
Element root=document.getRootElement();
Element b=root.addElement("book");
//3.创建各个节点
b.addAttribute("id", String.valueOf(data.size()+1));
b.addElement("bookId").setText(book.getBookId().toString());
b.addElement("bookName").setText(book.getBookName());
b.addElement("categoryId").setText(book.getCategoryId());
b.addElement("bookPrice").setText(book.getBookPrice().toString());
b.addElement("bookPic").setText(book.getBookPic());
b.addElement("remarks").setText(book.getRemarks());
//4.完成追加,写入xml
writer=new OutputStreamWriter(new FileOutputStream(dataFile),"UTF-8");
document.write(writer);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(writer!=null) {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
reloadBooks() ;
}
}
//按bookId进行删除
public static void deleteBook(Integer id) {
SAXReader reader=new SAXReader();
Writer writer=null;
try {
Document doucment=reader.read(dataFile);
List<Node>nodes=doucment.selectNodes("/root/book[@id="+id+"]");
if(nodes.size()==0) {
throw new RuntimeException("id="+id+"图书编号不存在");
}
Element b=(Element) nodes.get(0);
b.getParent().remove(b);
writer=new OutputStreamWriter(new FileOutputStream(dataFile),"UTF-8");
doucment.write(writer);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(writer!=null) {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
reloadBooks();
}
}
//更新
public static void update(Books book) {
SAXReader reader=new SAXReader();
Writer writer=null;
try {
Document document=reader.read(dataFile);
//节点路径[@属性名=属性值]
// /root/book[@id=x]
List<Node>nodes=document.selectNodes("/root/book[@id="+book.getId()+"]");
if(nodes.size()==0) {
throw new RuntimeException("id="+book.getId()+"图书编号不存在");
}
Element b = (Element)nodes.get(0);
b.selectSingleNode("bookId").setText(book.getBookId().toString());
b.selectSingleNode("bookName").setText(book.getBookName());
b.selectSingleNode("categoryId").setText(book.getCategoryId());
b.selectSingleNode("bookPrice").setText(book.getBookPrice().toString());
b.selectSingleNode("bookPic").setText(book.getBookPic());
b.selectSingleNode("remarks").setText(book.getRemarks());
writer = new OutputStreamWriter(new FileOutputStream(dataFile),"UTF-8");
document.write(writer);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
if(writer != null) {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
reloadBooks();
}
}
public static List<Books> bookData() {
return data;
}
public static List<Category> categoryData(){
return categoryData;
}
public static void main(String[] args) {
/*new XmlDataSource();
List<Books> bk=XmlDataSource.bookData();
System.out.println(bk);*/
//List<Category> cg=XmlDataSource.categoryData();
//System.out.println(cg);
/*Books b=new Books();
b.setBookId(1000);
b.setBookName("软件更新");
b.setCategoryId("计算机");
b.setBookPrice(100);
b.setBookPic("/image/g1.jpg");
b.setRemarks("测试");
//XmlDataSource.deleteBook(11010);*/
//Category c=new Category();
//c.setCategoryId(2);
//c.setCategoryName("计算机");
//XmlDataSource.deleteBook(3);
//List<Books> bk=XmlDataSource.bookData();
//System.out.println(bk);
}
}
udateBook.jsp:
<%@page contentType="text/html;charset=utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>修改图书信息</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/add.css">
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="js/validation.js"></script>
<script>
function checkSubmit() {
var a = checkEmpty("#bookId","#errBookId");
var b = checkEmpty('#bookName',"#errBname");
// var c = checkCategory('#categoryId',"#err");
var d = checkPrice('#bookPrice',"#errBookPrice");
var e = checkFile('#bookPic',"#errBookPic");
var f = checkEmpty('#remarks',"#errRemarks");
if (a && b && d && e && f) {
return true;
} else {
return false;
}
}
</script>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/dept/list.do">
图书信息管理
</a>
</div>
</div>
</nav>
<div class="container">
<div class="jumbotron">
<h1>Hello, XXX!</h1>
<p>请小心的修改图书信息。。。</p>
</div>
<div class="page-header">
<h3><small>修改</small></h3>
</div>
<form class="form-horizontal" action="/management?show_updateBook" method="post">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">图书编号 :</label>
<div class="col-sm-8">
<input name="bookId" class="form-control" id="bookId" readonly="readonly" onblur="checkEmpty('#bookId','#errBookId')" value="${book.bookId }">
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">图书名称 :</label>
<div class="col-sm-8">
<input name="bookName" class="form-control" id="bookName" onblur="checkEmpty('#bookName','#errBname')" value="${book.bookName }">
</div>
</div>
<div class="form-group">
<label for="categoryId" class="col-sm-2 control-label">分类 :</label>
<select id="categoryId" name="categoryId" class="col-sm-2 form-control" style="width: auto;margin-left: 15px">
<option value="ca0001" selected="">计算机</option>
<option value="ca0002">文学</option>
<option value="ca0003">历史</option>
<!-- 下拉列表的内容要从分类中进行读取,value值是分类id -->
</select>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">价格 :</label>
<div class="col-sm-8">
<input name="bookPrice" class="form-control" id="bookPrice" onblur="checkPrice('#bookPrice','#errBookPrice')" value="${book.bookPrice }">
</div>
</div>
<div class="form-group" >
<label for="name" class="col-sm-2 control-label">图书封面 :</label>
<input type="file" id="bookPic" name="bookPic" style="padding-left: 15px" onchange="checkFile('#bookPic','#errBookPic')">
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">备注 :</label>
<div class="col-sm-8">
<input name="remarks" class="form-control" id="remarks" onblur="checkEmpty('#remarks','#errRemarks')" value="${book.remarks}">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">修改</button>
</div>
</div>
</form>
</div>
<footer class="text-center" >
copy@imooc
</footer>
</body>
</html>
book.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!-- 数据文件 -->
<root>
<book id="1">
<bookId>11010</bookId>
<bookName>人生哲学</bookName>
<categoryId>文学</categoryId>
<bookPrice>20</bookPrice>
<bookPic>/upload/g1.jpg</bookPic>
<remarks>6666</remarks>
</book>
<book id="2">
<bookId>21010</bookId>
<bookName>软件工程</bookName>
<categoryId>计算机</categoryId>
<bookPrice>20</bookPrice>
<bookPic>/upload/g1.jpg</bookPic>
<remarks>6666</remarks>
</book>
<book id="3">
<bookId>31010</bookId>
<bookName>中国地理</bookName>
<categoryId>历史</categoryId>
<bookPrice>20</bookPrice>
<bookPic>/upload/g1.jpg</bookPic>
<remarks>6666</remarks>
</book>
<book id="4">
<bookId>41010</bookId>
<bookName>数据库原理</bookName>
<categoryId>计算机</categoryId>
<bookPrice>20</bookPrice>
<bookPic>/upload/g1.jpg</bookPic>
<remarks>6666</remarks>
</book>
<book id="5">
<bookId>51010</bookId>
<bookName>大明历程</bookName>
<categoryId>历史</categoryId>
<bookPrice>20</bookPrice>
<bookPic>/upload/g1.jpg</bookPic>
<remarks>6666</remarks>
</book>
</root>
bookList.jsp:
<%@page contentType="text/html;charset=utf-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>图书后台管理</title>
<link rel="stylesheet" href="css/index.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
<script src="js/sweetalert2.js" type="text/javascript"></script>
<script type="text/javascript">
//对话框显示预览图
function showPreview(previewObj){
var preview = $(previewObj).attr("data-preview");
var pname = $(previewObj).attr("data-pname");
Swal.fire({
title: pname,
html: "<img src='" + preview + "' style='width:361px;height:240px'>",
showCloseButton: true,
showConfirmButton: false
})
}
//删除数据
function del(delObj){
var id = $(delObj).attr("data-id");
var bookName = $(delObj).attr("data-pname");
var bookPic = $(delObj).attr("data-preview");
Swal.fire({
title : "确定要删除" + bookPic + "该图书吗?",
html : "<img src='" + bookPic + "' style='width:160px;height:90px'>",
showCancelButton: true,
confirmButtonText: "是",
cancelButtonText: "否"
}).then(function(result){
if(result.value==true){
//alert("你点了'是'按钮")
$.ajax({
url: "/management?method=deleteBook&id=" + id,
type : "get",
dataType:"json",
success : function(json){
if(json.result=="ok"){
window.location.reload();
}else{
Swal.fire({
title : json.result
})
}
//console.log(json);
}
})
}
})
}
</script>
</head>
<body>
<header>
<div class="container">
<nav>
<a href="/management?method=bookList">图书信息管理</a>
</nav>
<nav>
<a href="/management?method=categoryList">分类管理</a>
</nav>
</div>
</header>
<section class="banner">
<div class="container">
<div>
<h1>图书管理系统</h1>
<p>图书信息管理</p>
</div>
</div>
</section>
<section class="main">
<div class="container">
<form class="form-horizontal" action="/searchBook" method="post">
<div class="form-group" style="float: right;">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">查询</button>
</div>
</div>
<div class="form-group" style="float: right; width: 300px;">
<div class="col-sm-8">
<input name="searchContent" class="form-control"
id="searchContent" placeholder="输入要查询的分类" style="width: 250px">
</div>
</div>
</form>
</div>
<div class="container">
<table class="table table-striped">
<thead>
<tr>
<th>序号</th>
<th>图书编号</th>
<th>图书名称</th>
<th>分类</th>
<th>价格</th>
<th>图书封面</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<c:forEach items="${bookList }" var="bookList" varStatus="idx">
<tr>
<td>${idx.index + 1}</td>
<td>${bookList.bookId}</td>
<td>${bookList.bookName}</td>
<td>${bookList.categoryId}</td>
<td><fmt:formatNumber pattern="¥0.00"
value="${bookList.bookPrice}"></fmt:formatNumber></td>
<td><img src="${bookList.bookPic}"></td>
<td><a href="/management?method=show_updateBook&id=${bookList.id}">修改</a>
<a href="javascript:void(0)" data-id="${bookList.id }" data-pname="${bookList.bookName }" data-preview="${bookList.bookPic }" onclick="del(this)">删除</a>
<!--在循环显示数据时,此处的book0001可以用EL表达式进行替换-->
</tr>
</c:forEach>
</tbody>
</table>
</div>
</section>
<section class="page">
<div class="container">
<div id="fatie">
<a href="/management?method=show_addBook"><button>新建</button></a>
</div>
</div>
</section>
<footer> copy@慕课网 </footer>
</body>
</html>
相关截图:
17
收起
正在回答
2回答
同学你好,根据报错提示在ManagementController中的第57行出现了异常,根据报错提示显示是空指针异常
如下问题同学少写了method
另外这里应该添加
enctype="multipart/form-data"
祝学习愉快~
java工程师2020版
- 参与学习 人
- 提交作业 9393 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星