帮忙看下问题提示 ,还有功能上的

帮忙看下问题提示 ,还有功能上的

问题描述:

严重: 异常将上下文初始化事件发送到类的侦听器实例.[com.imooc.manage.entity.InitListener]
java.lang.ExceptionInInitializerError
    at com.imooc.manage.entity.InitListener.contextInitialized(InitListener.java:22)
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4705)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5171)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:183)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1412)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1402)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.NullPointerException
    at com.imooc.manage.utils.XmlDataSource.<clinit>(XmlDataSource.java:35)
    ... 10 more

四月 22, 2021 5:16:49 下午 org.apache.catalina.core.StandardContext startInternal
严重: 一个或多个listeners启动失败,更多详细信息查看对应的容器日志文件
四月 22, 2021 5:16:49 下午 org.apache.catalina.core.StandardContext startInternal
严重: 由于之前的错误,Context[]启动失败

相关代码:


package com.imooc.manage.controller;

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

import javax.servlet.ServletContext;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.imooc.manage.entity.Book;
import com.imooc.manage.entity.Category;
import com.imooc.manage.entity.User;
import com.imooc.manage.service.BookServiceImpl;
import com.imooc.manage.service.CategoryServiceImpl;
import com.imooc.manage.service.UserServiceImpl;
import com.imooc.manage.utils.PageModel;

/**
* Servlet implementation class ManageController
*/
@WebServlet("/management")
public class ManageController extends HttpServlet {
private BookServiceImpl bookService=new BookServiceImpl();
private CategoryServiceImpl categoryService=new CategoryServiceImpl();
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public ManageController() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
List<Book> bookData=(List)bookService.pagination(2,6);
request.setAttribute("bookData", bookData);
List<Category> categoryData =(List) categoryService.pagination(2,3);
request.setAttribute("categoryData", categoryData);
String method=request.getParameter("method");
if(method.equals("bookList")) {
this.bookList(request,response);
}else if(method.equals("deleteBook")) {
//this.delete(request,response);
}else if(method.equals("show_create")) {
this.showCreatePage(request,response);
}else if(method.equals("show_update")) {
this.showUpdatePage(request,response);
}else if(method.equals("categoryList")) {
this.categoryList(request, response);
}else if(method.equals("createCategory")) {
this.createCategory(request,response);
}else if(method.equals("login")) {
this.login(request,response);
}
// }else if(method.equals(deleteCategory)) {
// this.deleteCategory(request,response);
// }else if(method.equals("update")) {
//
// }
//
}
public void login(HttpServletRequest request,HttpServletResponse response) {
String userName=request.getParameter("userName");
String password=request.getParameter("password");
// HttpSession session=request.getSession();
// session.setAttribute("loginUser", userName);
User user=new User(userName,password);
ServletContext servletContext=request.getServletContext();
List<User> userList=(List<User>) servletContext.getAttribute("userList");
UserServiceImpl userService=new UserServiceImpl();
if(userService.login(userList, user)==1) {
request.getSession().setAttribute("user", user);
try {
request.getRequestDispatcher("/WEB-INF/jsp/bookList.jsp").forward(request, response);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
try {
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}


/**
* @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);
// }
//显示分类管理页面
public void categoryList(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/jsp/categoryList.jsp").forward(request, response);
}

//显示图书
private void bookList(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
String p=request.getParameter("p");
String r=request.getParameter("r");
if(p==null) {
p="2";
}
if(r==null) {
r="6";

}

PageModel pageModel=bookService.pagination(Integer.parseInt(p),Integer.parseInt(r));
request.setAttribute("pageModel", pageModel);
request.getRequestDispatcher("WEB-INF/jsp/bookList.jsp").forward(request,response);
}
//显示新增图书页面
public void showCreatePage(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("WEB-INF/jsp/addBook.jsp").forward(request, response);

}
//新增图书
public void createBook(HttpServletRequest request,HttpServletResponse response) {
// String bname=request.getParameter("bname");
// System.out.println(bname);
// request.getRequestDispatcher("/WEB-INF/jsp/addBook.jsp").forward(request, response);
//初始化Fileupload组件
FileItemFactory factory=new DiskFileItemFactory();

ServletFileUpload sf=new ServletFileUpload(factory);
//遍历FileItem
List<FileItem> formData;
try {
formData = sf.parseRequest(request);
Book book=new Book();
for(FileItem fi:formData) {
if(fi.isFormField()) {
System.out.println("普通输入项:"+fi.getFieldName()+":"+fi.getString("UTF-8"));
switch(fi.getFieldName()) {
case "bookName":
book.setBookName(fi.getString("UTF-8"));
break;
case "category":
book.setCategory(fi.getString("UTF-8"));
break;
case "price":
book.setPrice(Integer.parseInt(fi.getString("UTF-8")));
break;

case "remarks":
book.setRemarks(fi.getString("UTF-8"));
break;
default:
break;
}
}else {
System.out.println("文件上传项:"+fi.getFieldName());
//文件保存到服务器目录
String path=request.getServletContext().getRealPath("/upload");
System.out.println("文件上传目录:"+path);
String fileName=UUID.randomUUID().toString();
String suffix=fi.getName().substring(fi.getName().lastIndexOf("."));
fi.write(new File(path,fileName+suffix));
book.setBookPic("/upload"+fileName+suffix);

}
}
bookService.addBook(book);//新增书籍功能
response.sendRedirect("/management?method=bookList");//返回列表页

}catch(Exception e){
e.printStackTrace();
}

}
public void createCategory(HttpServletRequest request,HttpServletResponse response) throws IOException {
FileItemFactory factory=new DiskFileItemFactory();
//将前端表单数据转换为FileItem对象
ServletFileUpload sf=new ServletFileUpload(factory);
//用于为FileUpload组件提供java web层面上的http请求解析,增加对web的支持。
try {
List<FileItem> formData = sf.parseRequest(request);
Category category = new Category();
for(FileItem fi : formData) {
if(fi.isFormField()) {
switch (fi.getFieldName()) { //用于处理普通文本框
case "categoryId":
category.setCategoryId(fi.getString("UTF-8"));
break;
case "categoryName":
category.setCategoryName(fi.getString("UTF-8"));
break;
default:
break;
}
}
}
categoryService.addCategory(category);//此为新增功能,层层调用,controller,service,xmlData。
response.sendRedirect("/categoryList.jsp");//在填完表单之后返回
}catch(FileUploadException e) {
e.printStackTrace();
}
}
//按类别查询图书
public void search(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
String categoryName=request.getParameter("searchContent");

List<Book> bookData=bookService.getBooksByCatgoryName(categoryName);
request.getServletContext().setAttribute("bookData", bookData);
List<Category> categoryData=(List)categoryService.pagination(2, 3);
request.getServletContext().setAttribute("categoryData", categoryData);
request.setAttribute("searchContent", categoryName);
request.getRequestDispatcher("/WEB-INF/jsp/bookList.jsp").forward(request, response);
}
//显示更新页面
private void showUpdatePage(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
String id=request.getParameter("bookId");
Book book=bookService.getBooksById(id);
request.setAttribute("book", book);
request.getRequestDispatcher("/WEB-INF/jsp/updateBook.jsp").forward(request,response);

}

}


Book Controller:

package com.imooc.manage.controller;

import java.io.IOException;
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 com.imooc.manage.service.BookServiceImpl;
import com.imooc.manage.utils.PageModel;

/**
* Servlet implementation class BookController
*/
@WebServlet("/pagecontro")
public class BookController extends HttpServlet {
private static final long serialVersionUID = 1L;
private BookServiceImpl bookService=new BookServiceImpl();
/**
* @see HttpServlet#HttpServlet()
*/
public BookController() {
super();
// TODO Auto-generated constructor stub
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String page=request.getParameter("p");
String rows=request.getParameter("r");

if(page==null) {
page="2";

}
if(rows==null) {
rows="6";
}

PageModel pageModel=bookService.pagination(Integer.parseInt(page),Integer.parseInt(rows));
request.setAttribute("pageModel", pageModel);
request.getRequestDispatcher("/WEB-INF/jsp/bookList.jsp").forward(request, response);
}

}

BookDao:
package com.imooc.manage.dao;

import java.util.List;

import com.imooc.manage.entity.Book;
import com.imooc.manage.utils.PageModel;
import com.imooc.manage.utils.XmlDataSource;

public class BookDao {
//页面展示图书信息,通过XmlDataSource文件进行读取
public PageModel pagination(int page,int rows) {
List<Book> list=XmlDataSource.getBooks();
PageModel pageModel=new PageModel(list,page,rows);
return pageModel;
}
//新增图书
public void addBook(Book book) {
XmlDataSource.appendBook(book);
}
//通过bookId查找图书
public Book getBooksById(String bookId) {
List<Book> bookData=XmlDataSource.getBooks();
Book book=null;
for(Book b:bookData) {
if(b.getBookId()==Integer.parseInt(bookId)) {
book=b;
break;
}
}
return book;
}
//按categoryName查找图书
// public Book getBooksByCategoryName(String categoryName) {
// XmlDataSource.getBooksByCategoryName(categoryName);
// }
//删除图书
public void deleteBook(Integer id) {
XmlDataSource.deleteBook(id);
}
//更新图书
public void updateBook(Book book) {
XmlDataSource.updateBook(book);
}
}

​categoryDao:
​package com.imooc.manage.dao;

import java.util.List;


import com.imooc.manage.entity.Category;
import com.imooc.manage.utils.PageModel;
import com.imooc.manage.utils.XmlDataSource;

public class CategoryDao {
public PageModel pagination(int page,int rows) {
List<Category> list=XmlDataSource.getCategorys();
PageModel pageModel=new PageModel(list,page,rows);
return pageModel;
}
public void addCategory(Category category) {
XmlDataSource.appendCategory(category);
}
public void deleteCategory(String id) {
XmlDataSource.deleteCategory(id);
}
}

userDao:
​package com.imooc.manage.dao;

import java.util.List;


import com.imooc.manage.entity.User;
import com.imooc.manage.utils.PageModel;
import com.imooc.manage.utils.XmlDataSource;

public class UserDao {
public PageModel pagination(int page,int rows) {
List<User> listUser=XmlDataSource.getUsers();
PageModel pageModel=new PageModel(listUser,page,rows);
return pageModel;
}
}

AuthFilter:
package com.imooc.manage.entity;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthFilter implements Filter{

@Override
public void destroy() {
// TODO Auto-generated method stub

}

@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest req=(HttpServletRequest) arg0;
HttpServletResponse res=(HttpServletResponse) arg1;
HttpSession session =req.getSession();
User login=(User) session.getAttribute("login");
boolean flag=false;
String reqURI=req.getRequestURI();
//不需要过滤的url
String[] url= {".js",".ico",".css",".jsp",".html",".png","/login"};
for(String str:url) {
if(reqURI.indexOf(str)!=-1) {
flag=true;
break;
}
}
if(!flag) {
if(login!=null) {
chain.doFilter(req,res);
return;
}else {
res.sendRedirect(req.getContextPath()+"/login.jsp");
return;
}
}
chain.doFilter(req,res);
}

@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}

}
EncodeFilter:
​package com.imooc.manage.entity;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class EncodeFilter implements Filter{

@Override
public void destroy() {
// TODO Auto-generated method stub

}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletRequest req=(HttpServletRequest)request;
HttpServletResponse res=(HttpServletResponse)response;
req.setCharacterEncoding("UTF-8");
res.setCharacterEncoding("UTF-8");
chain.doFilter(request,response);
return;
}

@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub

}

}

InitListener:
package com.imooc.manage.entity;

import java.util.List;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import com.imooc.manage.utils.XmlDataSource;

public class InitListener implements ServletContextListener{

@Override
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub

}

@Override
public void contextInitialized(ServletContextEvent sre) {
// TODO Auto-generated method stub

List<User> userData=XmlDataSource.getUsers();
sre.getServletContext().setAttribute("listUser",userData);

}



}

​Book:
​package com.imooc.manage.entity;

public class Book {
private Integer id;
private Integer bookId;
private String bookName;
private String category;
private Integer price;
private String bookPic;
private String remarks;
public Book() {

}
public Book(Integer id,Integer bookId, String bookName,String category, Integer price, String bookPic, String remarks) {
super();
this.id=id;
this.bookId = bookId;
this.bookName = bookName;
this.category = category;
this.price = price;
this.bookPic = bookPic;
this.remarks = 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 getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
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;
}
@Override
public String toString() {
return "Book [id="+id+",bookId=" + bookId + ", bookName=" + bookName + ", category=" + category + ", price=" + price
+ ", bookPic=" + bookPic + ", remarks=" + remarks + "]";
}

}

Category:
package com.imooc.manage.entity;

public class Category {
private String categoryId;
private String categoryName;
public Category() {

}
public Category(String categoryId, String categoryName) {
super();
this.categoryId = categoryId;
this.categoryName = categoryName;
}
public String getCategoryId() {
return categoryId;
}
public void setCategoryId(String categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
@Override
public String toString() {
return "Category [categoryId=" + categoryId + ", categoryName=" + categoryName + "]";
}

}


​User:
​package com.imooc.manage.entity;

public class User {
private String userName;
private String password;
public User() {

}
public User(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User [userName=" + userName + ", password=" + password + "]";
}

}

BookServiceImpl:
package com.imooc.manage.service;

import java.util.List;

import com.imooc.manage.dao.BookDao;
import com.imooc.manage.entity.Book;
import com.imooc.manage.entity.Category;
import com.imooc.manage.utils.PageModel;
import com.imooc.manage.utils.XmlDataSource;

public class BookServiceImpl {
private BookDao bookDao=new BookDao();
public PageModel pagination(int page,int rows) {
if(rows==0) {
throw new RuntimeException("无效的rows参数");
}
return bookDao.pagination(page, rows);
}
public void addBook(Book book) {
bookDao.addBook(book);
}
public Book getBooksById(String bookId) {
Book b=bookDao.getBooksById(bookId);
if(b==null) {
throw new RuntimeException("[id="+bookId+"]书籍不存在");
}
return b;
}
public List<Book> getBooksByCatgoryName(String categoryName) {
List<Category> categoryData=XmlDataSource.getCategorys();
List<Book> bookData=XmlDataSource.getBooks();
List<Book> bookList=null;
for(Book b:bookData) {
for(Category c:categoryData) {
if(c.getCategoryName().equals(b.getCategory()))



bookList.add(b);
break;
}
break;
}
return bookList;
}
//删除图书
public void deleteBook(Integer id) {
bookDao.deleteBook(id);

// bookList.remove(book);
}
/**
* 更新业务
* @param newBook 新的图书数据
* @param isPreviewModified 是否修改bookPic属性
*/
public void update(Book newBook,Integer isPreviewModified) {
Book oldBook=this.getBooksById(String.valueOf(newBook.getId()));
oldBook.setBookId(newBook.getBookId());
oldBook.setBookName(newBook.getBookName());
oldBook.setPrice(newBook.getPrice());
oldBook.setRemarks(newBook.getRemarks());
if(isPreviewModified==1) {
oldBook.setBookPic(newBook.getBookPic());
}
bookDao.updateBook(oldBook);

}
public static void main(String[] args) {
BookServiceImpl bookService=new BookServiceImpl();
PageModel pageModel= bookService.pagination(2,6);
List<Book> BookList=pageModel.getPageData();
for(Book book:BookList) {
System.out.println(book.getBookName());
}
System.out.println(pageModel.getPageStartRow()+":"+pageModel.getPageEndRow());
}
}

CategoryServiceImpl:
​package com.imooc.manage.service;


import com.imooc.manage.dao.CategoryDao;
import com.imooc.manage.entity.Category;
import com.imooc.manage.utils.PageModel;

public class CategoryServiceImpl {
private CategoryDao categoryDao=new CategoryDao();
public PageModel pagination(int page,int rows) {
if(rows==0) {
throw new RuntimeException("无效的rows参数");
}
return categoryDao.pagination(page, rows);
}

public void addCategory(Category category) {
categoryDao.addCategory(category);
}
public void deleteCategory(String categoryId) {
categoryDao.deleteCategory(categoryId);
}
}

UserServiceImpl:
​package com.imooc.manage.service;


import java.util.List;

import com.imooc.manage.dao.UserDao;
import com.imooc.manage.entity.User;
/**
* 验证登录信息
* @param listUser 用户信息集合
* @param user 登录的用户
* @return 用户账号密码匹配成功则返回1,否则返回0
*/
public class UserServiceImpl {
private UserDao userDao=new UserDao();
public int login(List<User> listUser,User user) {
List<User> listUser1=(List)userDao.pagination(1,1);
if(user.getUserName()==null||user.getUserName().equals("")) {
return 0;
}else if(user.getPassword()==null||user.getPassword().equals("")) {
return 0;
}
for(User user1:listUser) {
if(user.getUserName().equals(user1.getUserName())&&user.getPassword().equals(user1.getPassword())) {
return 1;
}

}

return 0;

}
}


PageModel:

package com.imooc.manage.utils;

import java.util.ArrayList;
import java.util.List;

//分页模型对象
public class PageModel {
private int page;
private int totalPages;
private int rows;
private int totalRows;
private int pageStartRow;
private int pageEndRow;
private boolean hasNextPage;
private boolean hasPreviousPage;
private List pageData;//当前前页面数据
public PageModel() {

}
public PageModel(List data,int page,int rows) {
this.page=page;
this.rows=rows;
totalRows=data.size();
totalPages=new Double(Math.ceil(totalRows/(rows*1f))).intValue();
pageStartRow=(page-1)*rows;
pageEndRow=page*rows;
if(pageEndRow>totalRows) {//避免下标越界异常
pageEndRow=totalRows;
}
data.subList(pageStartRow,pageEndRow);//得到分页数据
if(page>1) {//判断是否有上一页
hasPreviousPage=true;
}else {
hasPreviousPage=false;
}
if(page<totalPages) {//判断是否存在下一页
hasNextPage=true;

}else {
hasNextPage=false;
}

}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public int getTotalPages() {
return totalPages;
}
public void setTotalPages(int totalPages) {
this.totalPages = totalPages;
}
public int getRows() {
return rows;
}
public void setRows(int rows) {
this.rows = rows;
}
public int getTotalRows() {
return totalRows;
}
public void setTotalRows(int totalRows) {
this.totalRows = totalRows;
}
public int getPageStartRow() {
return pageStartRow;
}
public void setPageStartRow(int pageStartRow) {
this.pageStartRow = pageStartRow;
}
public int getPageEndRow() {
return pageEndRow;
}
public void setPageEndRow(int pageEndRow) {
this.pageEndRow = pageEndRow;
}
public boolean isHasNextPage() {
return hasNextPage;
}
public void setHasNextPage(boolean hasNextPage) {
this.hasNextPage = hasNextPage;
}
public boolean isHasPreviousPage() {
return hasPreviousPage;
}
public void setHasPreviousPage(boolean hasPreviousPage) {
this.hasPreviousPage = hasPreviousPage;
}
public List getPageData() {
return pageData;
}
public void setPageData(List pageData) {
this.pageData = pageData;
}
public static void main(String[] args) {
List sam=new ArrayList();
for(int i=1;i<=100;i++) {
sam.add(i);

}
PageModel pageModel=new PageModel(sam,6,8);
System.out.println(pageModel.getPageData());
System.out.println(pageModel.getTotalPages());
System.out.println(pageModel.getPageStartRow()+":"+pageModel.getPageEndRow());

}
}



XmlDataSource:
package com.imooc.manage.utils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.dom4j.Document;

import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import com.imooc.manage.entity.Book;
import com.imooc.manage.entity.Category;
import com.imooc.manage.entity.User;

public class XmlDataSource {
private static List<User> userData;

private static List<Category> categoryData;

private static List<Book> bookData;

private static String userDataFile;

private static String categoryDataFile;

private static String bookDataFile;
static {
userData=new ArrayList<User>();
userDataFile=XmlDataSource.class.getResource("/user.xml").getPath();//获取数据路径
bookData=new ArrayList<Book>();
bookDataFile=XmlDataSource.class.getResource("/book.xml").getPath();
categoryData=new ArrayList<Category>();
categoryDataFile=XmlDataSource.class.getResource("/category.xml").getPath();
reloadUser();
reloadBooks();
reloadCategory();
}
//加载用户信息
public static void reloadUser() {
URLDecoder decoder =new URLDecoder();
try {
userDataFile=decoder.decode(userDataFile,"UTF-8");//将dataFile用UTF-8编码规定
System.out.println(userDataFile);
//利用dom4j对xml文件进行解析
SAXReader reader =new SAXReader();
Document document =reader.read(userDataFile);
//利用Xpath得到节点集合
List<Node> nodes=document.selectNodes("/root/user");//提取xml文件中的user节点
userData.clear();
for(Node node :nodes) {
Element element=(Element)node;
String id=element.attributeValue("id");
String userName=element.elementText("userName");
String password=element.elementText("password");
User user=new User();
user.setUserName(userName);
user.setPassword(password);
userData.add(user);
}

}catch(Exception e) {
e.printStackTrace();
}
}
//加载分类
public static void reloadCategory() {
URLDecoder decoder=new URLDecoder();
try {
categoryDataFile=decoder.decode(categoryDataFile,"UTF-8");
System.out.println(categoryDataFile);
SAXReader reader=new SAXReader();
Document document=reader.read(categoryDataFile);
List<Node> nodes=document.selectNodes("/root/category");
categoryData.clear();
for(Node node :nodes) {
Element element=(Element)node;
Category category=new Category();
category.setCategoryId(element.elementText("categoryId"));
category.setCategoryName(element.elementText("categoryName"));
categoryData.add(category);
}
}catch(Exception e){
e.printStackTrace();
}
}
//book读取
public static void reloadBooks() {

// 通过URLDecoder类将Base64转换成普通字符窜
//System.out.println(bookDataFile);
URLDecoder decoder=new URLDecoder();
try {
bookDataFile= decoder.decode(bookDataFile,"UTF-8");
//dom4j对xml解析
SAXReader reader=new SAXReader();
Document document=reader.read(bookDataFile);

List<Node> nodes=document.selectNodes("/root/book");
//清空集合
bookData.clear();
//遍历节点
for(Node node:nodes) {
Element element=(Element) node;
String id=element.attributeValue("id");
String bname=element.elementText("bname");

Book book=new Book();
book.setBookId(Integer.parseInt(id));
book.setBookName(bname);
book.setCategory(element.elementText("category"));
book.setPrice(Integer.parseInt(element.elementText("price")));
book.setBookPic(element.elementText("bookPic"));
book.setRemarks(element.elementText("remarks"));
bookData.add(book);
// System.out.println(id+":"+bname);
}
}catch(Exception e) {
e.printStackTrace();
}
}
public static List<User> getUsers(){
return userData;
}
public static List<Category> getCategorys(){
return categoryData;
}
public static List<Book> getBooks(){
return bookData;
}
//按id删除类别
public static void deleteCategory(String id) {
SAXReader reader=new SAXReader();
Writer writer=null;
try {
Document document=reader.read(categoryDataFile);
List<Node> categorynode=document.selectNodes("/root/category[@id="+id+"]");
if(categorynode.size()==0) {
throw new RuntimeException("id="+id+"分类编号不存在");

}
Element c=(Element)categorynode.get(0);
c.getParent().remove(c);
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();
}

}
//按id删除图书
public static void deleteBook(Integer id) {
SAXReader reader=new SAXReader();
Writer writer=null;
try {
Document doucment=reader.read(bookDataFile);
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(bookDataFile),"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 appendBook(Book book) {
//通过SAXReader读取xml文档,得到Document
SAXReader reader=new SAXReader();
Writer writer=null;
try {
Document document=reader.read(bookDataFile);
//2.创建book.xml的book节点
Element root=document.getRootElement();
Element b=root.addElement("book");
//创建各个节点
b.addAttribute("id", String.valueOf(bookData.size()+1));
b.addElement("bookId").setText(String.valueOf(book.getBookId()));
b.addElement("bookName").setText(book.getBookName());
b.addElement("category").setText(book.getCategory());
b.addElement("price").setText(String.valueOf(book.getPrice()));
b.addElement("bookPic").setText(book.getBookPic());
b.addElement("remarks").setText(book.getRemarks());
//转换字符流追加,写入xml
writer=new OutputStreamWriter(new FileOutputStream(bookDataFile),"UTF-8");
document.write(writer);
System.out.println(bookDataFile);
}catch(Exception e) {
e.printStackTrace();
}finally {
if(writer!=null) {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
reloadBooks();//保证内存中与文件数据一致
}
}
//新增类别
public static void appendCategory(Category category) {
SAXReader reader =new SAXReader();
Writer writer=null;
try {
Document document=reader.read(categoryDataFile);//读取文本数据
Element root=document.getRootElement();
Element p=root.addElement("category");
p.addAttribute("id", String.valueOf(categoryData.size()+1));
p.addElement("categoryId").setText(category.getCategoryId());
p.addElement("categoryName").setText(category.getCategoryName());
writer=new OutputStreamWriter(new FileOutputStream(categoryDataFile),"UTF-8");
document.write(writer);
//System.out.println(categoryDataFile);
}catch(Exception e) {
e.printStackTrace();
}finally {
if(writer!=null) {
try {
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
reloadCategory();
}
}
//更改图书
public static void updateBook(Book book) {
SAXReader reader=new SAXReader();
Writer writer=null;
try {
Document document=reader.read(bookDataFile);
//节点路径[@属性名=属性值]
// /root/book[@id=x]
List<Node> nodes=document.selectNodes("/root/book[@id="+book.getBookId()+"]");
if(nodes.size()==0) {
throw new RuntimeException("id="+book.getBookId()+"编号书籍不存在");

}
Element b=(Element)nodes.get(0);
b.selectSingleNode("bookName").setText(book.getBookName());
b.selectSingleNode("category").setText(book.getCategory());
b.selectSingleNode("price").setText(book.getPrice().toString());
b.selectSingleNode("bookPic").setText(book.getBookPic());
b.selectSingleNode("Remarks").setText(book.getRemarks());
writer=new OutputStreamWriter(new FileOutputStream(bookDataFile),"UTF-8");
document.write(writer);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(writer!=null) {
try {
writer.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
reloadBooks();
}
public static void main(String[] args) {
// new XmlDataSource();
// List<Book> bs=XmlDataSource.getBooks();
// System.out.println(bs);

//List<Category> cg=XmlDataSource.getCategorys();
//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.getBooks();
//System.out.println(bk);
List<User> u=XmlDataSource.getUsers();
System.out.println(u);

// XmlDataSource.appendBook(book);
}
}


正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

1回答
好帮手慕小班 2021-04-22 19:08:29

同学你好,1、NullPointerException,空指针异常,null调用方法或属性就会报出这个异常。

http://img1.sycdn.imooc.com//climg/608158400976a1eb07760164.jpg

    ​2、同学可以检查一下自己的XmlDataSource类的35行,是否出现null的内容,导致报出空指针异常。

http://img1.sycdn.imooc.com//climg/608158d90907f2bd10120224.jpg

    ​3、关于功能上的配置,同学可以将项目完成后,以作业的形式提交,会有专门的作业老师进行批复,便于调整同学的代码。

祝学习愉快!

  • 提问者 qq_慕神0589333 #1
    能详细点吗...
    2021-04-22 22:17:59
  • 好帮手慕小班 回复 提问者 qq_慕神0589333 #2

    同学你好,1、测试同学贴出的代码,并没有出现同学所描述的空指针异常,所以想让同学检查一下自己如下的代码是不是有问题,是哪个对象为null导致的。比如:

    http://img1.sycdn.imooc.com//climg/60822c52094c719f09880220.jpg

    或者同学也可以尝试清理一下缓存,再来重新启动试试。

    http://img1.sycdn.imooc.com//climg/60822d9d09d4011c02350225.jpg

        ​2、而关于功能上的配置,同学可以将项目完成后,以作业的形式将项目提交,会有专门的作业老师进行批复,也便于老师调整同学的代码。

    祝学习愉快!

    2021-04-23 10:14:57
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师