當前位置:
首頁 >
Java项目:在线购书商城系统(java+jsp+mysql+servlert+ajax)
發布時間:2023/12/10
44
豆豆
生活随笔
收集整理的這篇文章主要介紹了
Java项目:在线购书商城系统(java+jsp+mysql+servlert+ajax)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
源碼獲取:博客首頁 "資源" 里下載!
一、項目簡述
功能:一個基于JavaWeb的網上書店的設計與實現,歸納 出了幾個模塊,首先是登錄注冊模塊,圖書查找模塊,購 物車模塊,訂單模塊,個人中心模塊,用戶管理模塊,圖 書管理模塊等。 該項目是javaJeb技術的實戰操作,采用了MVC設計模 式,包括基本的entity, jscript, servlet,以及ajax異步請 求,查詢分頁,持久化層方法的封裝等等,對javaweb技 術的鞏固很有幫助,為J2EE的學習打下基礎,適用于課程 設計,畢業設計。
二、項目運行
環境配置: Jdk1.8 + Tomcat8.5 + mysql + Eclispe (IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)。
項目技術: JSP + Entity+ Servlert + html+ css + JavaScript + JQuery + Ajax + Fileupload 等等。
用戶信息控制層:
@Controller @RequestMapping("/user") public class UserController {@Autowiredprivate IUserService userService;@Autowiredprivate IMailService mailService;@Autowiredprivate IStoreService storeService;@Value("${mail.fromMail.addr}")private String from;@Value("${my.ip}")private String ip;private final String USERNAME_PASSWORD_NOT_MATCH = "用戶名或密碼錯誤";private final String USERNAME_CANNOT_NULL = "用戶名不能為空";@RequestMapping("/login")public String login(@RequestParam(value = "username", required = false) String username,@RequestParam(value = "password", required = false) String password,HttpServletRequest request, Model model) {if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {return "login";}//未認證的用戶Subject userSubject = SecurityUtils.getSubject();if (!userSubject.isAuthenticated()) {UsernamePasswordToken token = new UsernamePasswordToken(username, password);token.setRememberMe(false);//禁止記住我功能try {//登錄成功userSubject.login(token);User loginUser = (User) userSubject.getPrincipal();request.getSession().setAttribute("loginUser", loginUser);Store store = storeService.findStoreByUserId(loginUser.getUserId());request.getSession().setAttribute("loginStore", store);SavedRequest savedRequest = WebUtils.getSavedRequest(request);String url = "/";if (savedRequest != null) {url = savedRequest.getRequestUrl();if(url.contains(request.getContextPath())){url = url.replace(request.getContextPath(),"");}}if(StringUtils.isEmpty(url) || url.equals("/favicon.ico")){url = "/";}return "redirect:" + url;} catch (UnknownAccountException | IncorrectCredentialsException uae) {model.addAttribute("loginMsg", USERNAME_PASSWORD_NOT_MATCH);return "login";} catch (LockedAccountException lae) {model.addAttribute("loginMsg", "賬戶已被凍結!");return "login";} catch (AuthenticationException ae) {model.addAttribute("loginMsg", "登錄失敗!");return "login";}} else {//用戶已經登錄return "redirect:/index";}}@RequestMapping("/info")public String personInfo(){return "user_info";}/* @RequestMapping("/login1")public String login1(@RequestParam(value = "username", required = false) String username,@RequestParam(value = "password", required = false) String password,Model model, HttpServletRequest request) {if (StringUtils.isEmpty(username)) {model.addAttribute("loginMsg", USERNAME_CANNOT_NULL);return "login";}if (StringUtils.isEmpty(password)) {model.addAttribute("loginMsg", "密碼不能為空");return "login";}BSResult<User> bsResult = userService.login(username, password);//登錄校驗失敗if (bsResult.getData() == null) {model.addAttribute("loginMsg", bsResult.getMessage());return "login";}//登錄校驗成功,重定向到首頁User user = bsResult.getData();//置密碼為空user.setPassword("");request.getSession().setAttribute("user", user);return "redirect:/";}*///shiro框架幫我們注銷@RequestMapping("/logout")@CacheEvict(cacheNames="authorizationCache",allEntries = true)public String logout() {SecurityUtils.getSubject().logout();return "redirect:/page/login";}/*** 注冊 檢驗用戶名是否存在** @param username* @return*/@RequestMapping("/checkUserExist")@ResponseBodypublic BSResult checkUserExist(String username) {if (StringUtils.isEmpty(username)) {return BSResultUtil.build(200, USERNAME_CANNOT_NULL, false);}return userService.checkUserExistByUsername(username);}/*** 注冊,發激活郵箱** @param user* @return*/@RequestMapping("/register")public String register(User user, Model model) {BSResult isExist = checkUserExist(user.getUsername());//盡管前臺頁面已經用ajax判斷用戶名是否存在,// 為了防止用戶不是點擊前臺按鈕提交表單造成的錯誤,后臺也需要判斷if ((Boolean) isExist.getData()) {user.setActive("1");BSResult bsResult = userService.saveUser(user);//獲得未激活的用戶User userNotActive = (User) bsResult.getData();/* try {mailService.sendHtmlMail(user.getEmail(), "<dd書城>---用戶激活---","<html><body><a href='http://"+ip+"/user/active?activeCode=" + userNotActive.getCode() + "'>親愛的" + user.getUsername() +",請您點擊此鏈接前往激活</a></body></html>");} catch (Exception e) {e.printStackTrace();model.addAttribute("registerError", "發送郵件異常!請檢查您輸入的郵箱地址是否正確。");return "fail";}*/model.addAttribute("username", user.getUsername());return "register_success";} else {//用戶名已經存在,不能注冊model.addAttribute("registerError", isExist.getMessage());return "register";}}@RequestMapping("/active")public String activeUser(String activeCode, Model model) {BSResult bsResult = userService.activeUser(activeCode);if (!StringUtils.isEmpty(bsResult.getData())) {model.addAttribute("username", bsResult.getData());return "active_success";} else {model.addAttribute("failMessage", bsResult.getMessage());return "fail";}}@RequestMapping("/update")@ResponseBodypublic BSResult updateUser(User user, HttpSession session){User loginUser = (User) session.getAttribute("loginUser");loginUser.setNickname(user.getNickname());loginUser.setLocation(user.getLocation());loginUser.setDetailAddress(user.getDetailAddress());loginUser.setGender(user.getGender());loginUser.setUpdated(new Date());loginUser.setPhone(user.getPhone());loginUser.setIdentity(user.getIdentity());loginUser.setPhone(user.getPhone());BSResult bsResult = userService.updateUser(loginUser);session.setAttribute("loginUser", loginUser);return bsResult;}@RequestMapping("/password/{userId}")@ResponseBodypublic BSResult changePassword(@PathVariable("userId") int userId,String oldPassword,String newPassword){if(StringUtils.isEmpty(oldPassword) || StringUtils.isEmpty(newPassword)){return BSResultUtil.build(400, "密碼不能為空");}return userService.compareAndChange(userId,oldPassword,newPassword);}}訂單控制層:
@Controller @RequestMapping("/order") public class OrderController {@Autowiredprivate IOrderService orderService;@Autowiredprivate ICartService cartService;@Autowiredprivate IBookInfoService bookInfoService;/*** 填寫訂單信息頁面** @param bookId* @param buyNum* @param request* @return*/@GetMapping("/info")public String orderInfo(@RequestParam(required = false, defaultValue = "0") int bookId,@RequestParam(required = false, defaultValue = "0") int buyNum,HttpServletRequest request) throws BSException {if (bookId != 0) {//點了立即購買,放到request域中,也session的立即購買域中以區分購物車中的書籍BookInfo bookInfo = bookInfoService.findById(bookId);if (bookInfo != null) {BSResult bsResult = cartService.addToCart(bookInfo, null, buyNum);request.getSession().setAttribute("buyNowCart", bsResult.getData());request.setAttribute("cart", bsResult.getData());return "order_info";} else {request.setAttribute("exception", "不好意思,書籍庫存不足或不存在了!");return "exception";}}//沒有點立即購買,購物車中的總金額大于0才讓填寫訂單信息Cart cart = (Cart) request.getSession().getAttribute("cart");if (cart != null && cart.getTotal() > 0) {return "order_info";} else {return "cart";}}@GetMapping("/payPage/{orderId}")public String toPay(@PathVariable("orderId") String orderId, Model model) {BSResult bsResult = orderService.findOrderById(orderId);if (bsResult.getCode() == 200) {model.addAttribute("order", bsResult.getData());return "payment";}return "exception";}@RequestMapping("/deletion/{orderId}")public String deletion(@PathVariable("orderId") String orderId) {BSResult bsResult = orderService.deleteOrder(orderId);if (bsResult.getCode() == 200) {return "redirect:/order/list";}return "exception";}/*** 訂單列表** @return*/@GetMapping("/list")public String orderList(HttpServletRequest request) {User loginUser = (User) request.getSession().getAttribute("loginUser");List<OrderCustom> orderCustoms = orderService.findOrdersByUserId(loginUser.getUserId());request.setAttribute("orderCustoms", orderCustoms);return "order_list";}/*** 創建訂單** @return*/@PostMapping("/creation")public String createOrder(User userDTO, String express, int payMethod, HttpServletRequest request) {//立即購買,優先創建訂單Cart buyNowCart = (Cart) request.getSession().getAttribute("buyNowCart");User loginUser = (User) request.getSession().getAttribute("loginUser");userDTO.setUserId(loginUser.getUserId());userDTO.setZipCode(loginUser.getZipCode());if (buyNowCart != null) {BSResult bsResult = orderService.createOrder(buyNowCart, userDTO, express, payMethod);if (bsResult.getCode() == 200) {request.setAttribute("order", bsResult.getData());cartService.clearCart(request, "buyNowCart");return "payment";} else {request.setAttribute("exception", bsResult.getMessage());return "exception";}}//普通購物車Cart cart = (Cart) request.getSession().getAttribute("cart");if (cart != null) {BSResult bsResult = orderService.createOrder(cart, userDTO, express, payMethod);if (bsResult.getCode() == 200) {request.setAttribute("order", bsResult.getData());cartService.clearCart(request, "cart");return "payment";} else {request.setAttribute("exception", bsResult.getMessage());return "exception";}} else {request.setAttribute("exception", "購物車為空!");return "exception";}}/*** 確認收貨** @param orderId* @return*/@RequestMapping("/confirm/{orderId}")public String confirmReceiving(@PathVariable("orderId") String orderId, Model model) {BSResult bsResult = orderService.confirmReceiving(orderId);if (bsResult.getCode() == 200) {return "redirect:/order/list";} else {model.addAttribute("exception", bsResult.getMessage());return "exception";}} }書籍信息控制層:
@Controller @RequestMapping("/book") public class BookInfoController {@Autowiredprivate IBookInfoService bookInfoService;@Autowiredprivate BookDescMapper bookDescMapper;/*** 查詢某一本書籍詳情** @param bookId* @param model* @return*/@RequestMapping("/info/{bookId}")public String bookInfo(@PathVariable("bookId") Integer bookId, Model model) throws BSException {//查詢書籍BookInfo bookInfo = bookInfoService.findById(bookId);//查詢書籍推薦列表List<BookInfo> recommendBookList = bookInfoService.findBookListByCateId(bookInfo.getBookCategoryId(), 1, 5);//查詢書籍詳情BookDesc bookDesc = bookDescMapper.selectByPrimaryKey(bookId);//增加訪問量bookInfoService.addLookMount(bookInfo);Collections.shuffle(recommendBookList);model.addAttribute("bookInfo", bookInfo);model.addAttribute("bookDesc", bookDesc);model.addAttribute("recommendBookList", recommendBookList);return "book_info";}/*** 通過關鍵字和書籍分類搜索書籍列表** @param keywords* @return*/@RequestMapping("/list")public String bookSearchList(@RequestParam(defaultValue = "", required = false) String keywords,@RequestParam(defaultValue = "0", required = false) int cateId,//分類Id,默認為0,即不按照分類Id查@RequestParam(defaultValue = "1", required = false) int page,@RequestParam(defaultValue = "6", required = false) int pageSize,Model model) {keywords = keywords.trim();PageInfo<BookInfo> bookPageInfo = bookInfoService.findBookListByCondition(keywords, cateId, page, pageSize,0);//storeId為0,不按照商店Id查詢model.addAttribute("bookPageInfo", bookPageInfo);model.addAttribute("keywords", keywords);model.addAttribute("cateId", cateId);return "book_list";}}源碼獲取:博客首頁 "資源" 里下載!
總結
以上是生活随笔為你收集整理的Java项目:在线购书商城系统(java+jsp+mysql+servlert+ajax)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 实例47:python
- 下一篇: mysql一直拒绝登录_mysql 登录