Day14

2022/1/18 23:36:17

本文主要是介绍Day14,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

BusinessService类

public interface BusinessService {
    void addBook(Book book);
    
    Page findAllBook(String pagenum);
    
        void userRegister(User user);
    
        User userLogin(String username ,String password,String type);
    
    void addCategory(Category category);
    
    Category findCategoryById(String id);    
    
    List<Category> findAllCategory();
    
    void delCategory(String categoryId);

    void editCategory(Category category);

    void delBook(String bookId);

    Book findBookById(String bookId);

    void editBook(Book book);

    Page findAllBookPageRecords(String pagenum, String categoryId);
}
View Code

BusinessServiceImpl类

public class BusinessServiceImpl implements BusinessService {
    
    
    BookDao bookDao = new BookDaoImpl();
    UserDao userDao = new UserDaoImpl();
    CategoryDao categoryDao = new CategoryDaoImpl();
    
    public void addBook(Book book) {
        book.setId(UUID.randomUUID().toString());
        bookDao.insertBook(book);
    }

    
    
    public void delBook(String bookId) {
        bookDao.remove(bookId);
    }
    
    public Book findBookById(String bookId) {
        Book book = bookDao.getBookById(bookId);
        return book;
    }
    
    public void editBook(Book book) {
        bookDao.updateBook(book);
        
    }

    public Page findAllBook(String pagenum) {
        
        int currentPagenum = 1;
        if(pagenum != null){
            currentPagenum = Integer.parseInt(pagenum);
        }
        
        int totalRecords = bookDao.findAllBookNumber();
                         
        Page page = new Page(currentPagenum, totalRecords);
        
        List<Book> records = bookDao.findAllBookRecords(page.getStartIndex(), page.getPageSize());
        
        page.setRecords(records);
        
        System.out.println("page = " +page);
        
        return page;
    }
    
    @Override
    public Page findAllBookPageRecords(String pagenum, String categoryId) {
        int currentPagenum = 1;
        if(pagenum != null){
            currentPagenum = Integer.parseInt(pagenum);
        }
        
        int totalRecords = bookDao.findPageBookNumber(categoryId);
                         
        Page page = new Page(currentPagenum, totalRecords);
        
        List<Book> records = bookDao.findPageBooks(page.getStartIndex(), page.getPageSize(),categoryId);
        
        page.setRecords(records);
        
        System.out.println("page = " +page);
        
        return page;
    }

    public void addCategory(Category category) {
        category.setId(UUID.randomUUID().toString());
        categoryDao.save(category);
    }


    public Category findCategoryById(String id) {
        return categoryDao.getCategoryById(id);
    }

    
    public List<Category> findAllCategory() {
        return categoryDao.getAllCategory();
    }

    
    public void delCategory(String categoryId) {
        categoryDao.removeCategory(categoryId);
        
    }

    public void editCategory(Category category) {
        categoryDao.updateCategory(category);
        
    }
        
    public void userRegister(User user) {
        user.setId(UUID.randomUUID().toString());
        System.out.println("service中的user是"+user);
        userDao.save(user);
    }

    public User userLogin(String username, String password,String type) {
        return userDao.login(username,password,type);
}
View Code

servlet包ControlServlet类

public class ControlServlet extends HttpServlet {

	BusinessService s = new BusinessServiceImpl();

	Book book = new Book();

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		
		response.setCharacterEncoding("utf-8");
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		String op = request.getParameter("op");

		if ("addCategory".equals(op)) {
			addCategory(request, response);
			// 如果传过来的参数是“findAllCategory” 与 op的值相同
		} else if ("showBookDetails".equals(op)) {
			showBookDetails(request, response);
		} else if ("showIndex".equals(op)) {
			showIndex(request, response);
		} else if ("showCategoryBooks".equals(op)) {
			showCategoryBooks(request, response);
		} else if ("buyBook".equals(op)) {
			buyBook(request, response);
		} else if ("changeNum".equals(op)) {
			changeNum(request, response);
		} else if("delOneItem".equals(op)){
			delOneItem(request,response);
		}else if ("findAllCategory".equals(op)) {
			findAllCategory(request, response);
		} else if ("userRegister".equals(op)) {
			userRegister(request, response);
		} else if ("userLogin".equals(op)) {
			userLogin(request, response);
		} else if ("logout".equals(op)) {
			logout(request, response);
		} else if ("addBookView".equals(op)) {
			addBookView(request, response);
		} else if ("addBook".equals(op)) {
			addBook(request, response);
		} else if ("showBook".equals(op)) {
			showBook(request, response);
		} else if ("delCategory".equals(op)) {
			delCategory(request, response);
		} else if ("editCategoryView".equals(op)) {
			editCategoryView(request, response);
		} else if ("editCategory".equals(op)) {
			editCategory(request, response);
		} else if ("delBook".equals(op)) {
			delBook(request, response);
		} else if ("editBookView".equals(op)) {
			editBookView(request, response);
		} else if ("editBook".equals(op)) {
			editBook(request, response);
		}
	}

	
	//  删除购物项目
	private void delOneItem(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		
		String bookId = request.getParameter("bookId");
		
		Cart cart = (Cart) request.getSession().getAttribute("cart");
	
		cart.getItems().remove(bookId);
		
		// 重定向
		response.sendRedirect(request.getContextPath()+"/showCart.jsp");
		
	}

	
	 // 修改购物项的数量
	private void changeNum(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		String bookId = request.getParameter("bookId");
		String newNum = request.getParameter("num");
		
		Cart cart = (Cart) request.getSession().getAttribute("cart");
		CartItem item = cart.getItems().get(bookId);
		item.setQuantity(Integer.parseInt(newNum));
		
		// 重定向
		response.sendRedirect(request.getContextPath()+"/showCart.jsp");
		
		
		
	}

	//购买书籍
	private void buyBook(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String bookId = request.getParameter("bookId");

		Book b = s.findBookById(bookId);

		HttpSession session = request.getSession();

		Cart cart = (Cart) session.getAttribute("cart");

		if (cart == null) {
			cart = new Cart();
			session.setAttribute("cart", cart);
		}
		cart.addBook(b);
		System.out.println("cart" + cart.getItems());
		request.setAttribute("msg",
				"书籍购买成功,<a href='" + request.getContextPath() + "'>请继续购物!</a>");
		request.getRequestDispatcher("/message.jsp").forward(request, response);

	}

	//展示图书的详细信息
	 private void showBookDetails(HttpServletRequest request,
	HttpServletResponse response) throws ServletException, IOException {
	String bookId = request.getParameter("bookId");
	Book b = s.findBookById(bookId);
	request.setAttribute("b", b);

	request.getRequestDispatcher("/showBookDetails.jsp").forward(request,
				response);

	}

		private void showCategoryBooks(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String pagenum = request.getParameter("pagenum");
		String categoryId = request.getParameter("categoryId");

		List<Category> cs = s.findAllCategory();

		Page page = s.findAllBookPageRecords(pagenum, categoryId);

		page.setUrl("servlet/ControlServlet?op=showCategoryBooks&categoryId="
				+ categoryId);

		request.setAttribute("page", page);
		request.setAttribute("cs", cs);

		request.getRequestDispatcher("/showAllBooks.jsp").forward(request,
				response);
	}

	//展示一个首页
	private void showIndex(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String pagenum = request.getParameter("pagenum");

		Page page = s.findAllBook(pagenum);

		page.setUrl("servlet/ControlServlet?op=showIndex");

		List<Category> cs = s.findAllCategory();

		request.setAttribute("page", page);
		request.setAttribute("cs", cs);

		request.getRequestDispatcher("/showAllBooks.jsp").forward(request,
				response);

	}

	
	 // 用户注销:退出登录、跳转到index.jsp
	private void logout(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		request.getSession().invalidate();
		response.sendRedirect(request.getContextPath());
	}


	//编辑图书:更新内容
	private void editBook(HttpServletRequest request,
			HttpServletResponse response) {

		String bookId = request.getParameter("bookId");

		try {
			// 不是一个普通的表单
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			if (!isMultipart) {
				// 普通的表单
				request.setAttribute("msg", "亲,您的表单填写有误,请检查!");
				request.getRequestDispatcher("/message.jsp").forward(request,
						response);
				// 表示判断语句结束
				return;
			}
			DiskFileItemFactory factory = new DiskFileItemFactory();
			ServletFileUpload upload = new ServletFileUpload(factory);

			List<FileItem> items = upload.parseRequest(request);
			for (FileItem item : items) {
				if (item.isFormField()) {

					String fieldName = item.getFieldName();
					String fieldValue = item.getString(request
							.getCharacterEncoding());
					BeanUtils.setProperty(book, fieldName, fieldValue);
					book.setId(bookId);
				} else {
					if (fieldName != null && !fieldName.trim().equals("")) {
						String storeDirectory = getServletContext()
								.getRealPath("/images/");
						// 路径
						String path = SetPhotoPath.makeDir(storeDirectory,
								fieldName);
												book.setPath(path);
						book.setPhotoName(fieldName);

						// 上传
						item.write(new File(storeDirectory + path + "/"
								+ fieldName));

					}
				}
			}

			System.out.println("book:" + book);

			s.editBook(book);
			request.setAttribute("msg", "修改图书成功!");
			request.getRequestDispatcher("/message.jsp").forward(request,
					response);

		} catch (Exception e) {
			throw new RuntimeException(e);
		}

	}

	private void editBookView(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String bookId = request.getParameter("bookId");

		Book b = s.findBookById(bookId);

		List<Category> cs = s.findAllCategory();

		request.setAttribute("cs", cs);

		request.setAttribute("b", b);

		request.getRequestDispatcher("/editBook.jsp")
				.forward(request, response);

	}

  



这篇关于Day14的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程