Java畢業設計實戰項目之在線服裝銷售商城系統的實現流程

一、項目運行

環境配置:

Jdk1.8 + Tomcat8.5 + Mysql + HBuilderX(Webstorm也行)+ Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)。

項目技術:

Spring + SpringBoot+ mybatis + Maven + Vue 等等組成,B/S模式 + Maven管理等等。

後臺管理-用戶頁:

/**
 * 後臺管理-用戶頁
 */
@Controller
public class UserController extends BaseController{
    @Resource(name="userService")
    private UserService userService;
    @Resource(name="addressService")
    private AddressService addressService;
    @Resource(name ="reviewService")
    private ReviewService reviewService;
    @Resource(name = "productOrderItemService")
    private ProductOrderItemService productOrderItemService;
    @Resource(name = "productService")
    private ProductService productService;
    @Resource(name = "productImageService")
    private ProductImageService productImageService;
 
    //轉到後臺管理-用戶頁-ajax
    @RequestMapping(value = "admin/user", method = RequestMethod.GET)
    public String goUserManagePage(HttpSession session, Map<String, Object> map){
        logger.info("獲取前十條用戶信息");
        PageUtil pageUtil = new PageUtil(0, 10);
        List<User> userList = userService.getList(null, null, pageUtil);
        map.put("userList", userList);
        logger.info("獲取用戶總數量");
        Integer userCount = userService.getTotal(null);
        map.put("userCount", userCount);
        logger.info("獲取分頁信息");
        pageUtil.setTotal(userCount);
        map.put("pageUtil", pageUtil);
 
        logger.info("轉到後臺管理-用戶頁-ajax方式");
        return "admin/userManagePage";
    }
 
 
    //轉到後臺管理-用戶詳情頁-ajax
    @RequestMapping(value = "admin/user/{uid}", method = RequestMethod.GET)
    public String getUserById(HttpSession session, Map<String,Object> map, @PathVariable Integer uid/* 用戶ID */){
        logger.info("獲取user_id為{}的用戶信息",uid);
        User user = userService.get(uid);
        logger.info("獲取用戶詳情-所在地地址信息");
        Address address = addressService.get(user.getUser_address().getAddress_areaId());
        Stack<String> addressStack = new Stack<>();
        //最後一級地址
        addressStack.push(address.getAddress_name() + " ");
        //如果不是第一級地址
        while (!address.getAddress_areaId().equals(address.getAddress_regionId().getAddress_areaId())) {
            address = addressService.get(address.getAddress_regionId().getAddress_areaId());
            addressStack.push(address.getAddress_name() + " ");
        }
        StringBuilder builder = new StringBuilder();
        while (!addressStack.empty()) {
            builder.append(addressStack.pop());
        }
        logger.info("所在地地址字符串:{}", builder);
        user.setUser_address(new Address().setAddress_name(builder.toString()));
 
        logger.info("獲取用戶詳情-傢鄉地址信息");
        address = addressService.get(user.getUser_homeplace().getAddress_areaId());
        //最後一級地址
        addressStack.push(address.getAddress_name() + " ");
        //如果不是第一級地址
        while (!address.getAddress_areaId().equals(address.getAddress_regionId().getAddress_areaId())) {
            address = addressService.get(address.getAddress_regionId().getAddress_areaId());
            addressStack.push(address.getAddress_name() + " ");
        }
        builder = new StringBuilder();
        while (!addressStack.empty()) {
            builder.append(addressStack.pop());
        }
        logger.info("傢鄉地址字符串:{}", builder);
        user.setUser_homeplace(new Address().setAddress_name(builder.toString()));
 
        logger.info("獲取用戶詳情-購物車訂單項信息");
        List<ProductOrderItem> productOrderItemList = productOrderItemService.getListByUserId(
                user.getUser_id(), null
        );
        if (productOrderItemList != null) {
            logger.info("獲取用戶詳情-購物車訂單項對應的產品信息");
            for (ProductOrderItem productOrderItem : productOrderItemList) {
                Integer productId = productOrderItem.getProductOrderItem_product().getProduct_id();
                logger.warn("獲取產品ID為{}的產品信息", productId);
                Product product = productService.get(productId);
                if (product != null) {
                    logger.warn("獲取產品ID為{}的第一張預覽圖片信息", productId);
                    product.setSingleProductImageList(productImageService.getList(
                            productId, (byte) 0, new PageUtil(0, 1))
                    );
                }
                productOrderItem.setProductOrderItem_product(product);
            }
        }
        user.setProductOrderItemList(productOrderItemList);
 
        if (user.getUser_realname() != null) {
            logger.info("用戶隱私加密");
            user.setUser_realname(user.getUser_realname().substring(0, 1) + "*");
        } else {
            user.setUser_realname("未命名");
        }
 
        map.put("user",user);
 
        logger.info("轉到後臺管理-用戶詳情頁-ajax方式");
        return "admin/include/userDetails";
    }
 
    //按條件查詢用戶-ajax
    @ResponseBody
    @RequestMapping(value = "admin/user/{index}/{count}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public String getUserBySearch(@RequestParam(required = false) String user_name/* 用戶名稱 */,
                                  @RequestParam(required = false) Byte[] user_gender_array/* 用戶性別數組 */,
                                  @RequestParam(required = false) String orderBy/* 排序字段 */,
                                  @RequestParam(required = false,defaultValue = "true") Boolean isDesc/* 是否倒序 */,
                                  @PathVariable Integer index/* 頁數 */,
                                  @PathVariable Integer count/* 行數 */) throws UnsupportedEncodingException {
        //移除不必要條件
        Byte gender = null;
        if (user_gender_array != null && user_gender_array.length == 1) {
            gender = user_gender_array[0];
        }
 
        if (user_name != null) {
            //如果為非空字符串則解決中文亂碼:URLDecoder.decode(String,"UTF-8");
            user_name = "".equals(user_name) ? null : URLDecoder.decode(user_name, "UTF-8");
        }
        if (orderBy != null && "".equals(orderBy)) {
            orderBy = null;
        }
        //封裝查詢條件
        User user = new User()
                .setUser_name(user_name)
                .setUser_gender(gender);
 
        OrderUtil orderUtil = null;
        if (orderBy != null) {
            logger.info("根據{}排序,是否倒序:{}",orderBy,isDesc);
            orderUtil = new OrderUtil(orderBy, isDesc);
        }
 
        JSONObject object = new JSONObject();
        logger.info("按條件獲取第{}頁的{}條用戶", index + 1, count);
        PageUtil pageUtil = new PageUtil(index, count);
        List<User> userList = userService.getList(user, orderUtil, pageUtil);
        object.put("userList", JSONArray.parseArray(JSON.toJSONString(userList)));
        logger.info("按條件獲取用戶總數量");
        Integer userCount = userService.getTotal(user);
        object.put("userCount", userCount);
        logger.info("獲取分頁信息");
        pageUtil.setTotal(userCount);
        object.put("totalPage", pageUtil.getTotalPage());
        object.put("pageUtil", pageUtil);
 
        return object.toJSONString();
    }
}

後臺管理-產品類型頁:

/**
 * 後臺管理-產品類型頁
 */
@Controller
public class CategoryController extends BaseController {
    @Resource(name = "categoryService")
    private CategoryService categoryService;
    @Resource(name = "lastIDService")
    private LastIDService lastIDService;
    @Resource(name = "propertyService")
    private PropertyService propertyService;
 
    //轉到後臺管理-產品類型頁-ajax
    @RequestMapping(value = "admin/category", method = RequestMethod.GET)
    public String goToPage(HttpSession session, Map<String, Object> map) {
        logger.info("獲取前10條產品類型列表");
        PageUtil pageUtil = new PageUtil(0, 10);
        List<Category> categoryList = categoryService.getList(null, pageUtil);
        map.put("categoryList", categoryList);
        logger.info("獲取產品類型總數量");
        Integer categoryCount = categoryService.getTotal(null);
        map.put("categoryCount", categoryCount);
        logger.info("獲取分頁信息");
        pageUtil.setTotal(categoryCount);
        map.put("pageUtil", pageUtil);
 
        logger.info("轉到後臺管理-分類頁-ajax方式");
        return "admin/categoryManagePage";
    }
 
    //轉到後臺管理-產品類型詳情頁-ajax
    @RequestMapping(value = "admin/category/{cid}", method = RequestMethod.GET)
    public String goToDetailsPage(HttpSession session, Map<String, Object> map, @PathVariable Integer cid/* 分類ID */) {
        logger.info("獲取category_id為{}的分類信息", cid);
        Category category = categoryService.get(cid);
        logger.info("獲取分類子信息-屬性列表");
        category.setPropertyList(propertyService.getList(new Property().setProperty_category(category), null));
        map.put("category", category);
 
        logger.info("轉到後臺管理-分類詳情頁-ajax方式");
        return "admin/include/categoryDetails";
    }
 
    //轉到後臺管理-產品類型添加頁-ajax
    @RequestMapping(value = "admin/category/new", method = RequestMethod.GET)
    public String goToAddPage(HttpSession session, Map<String, Object> map) {
        logger.info("轉到後臺管理-分類添加頁-ajax方式");
        return "admin/include/categoryDetails";
    }
 
    //添加產品類型信息-ajax
    @ResponseBody
    @RequestMapping(value = "admin/category", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public String addCategory(@RequestParam String category_name/* 分類名稱 */,
                              @RequestParam String category_image_src/* 分類圖片路徑 */) {
        JSONObject jsonObject = new JSONObject();
        logger.info("整合分類信息");
        Category category = new Category()
                .setCategory_name(category_name)
                .setCategory_image_src(category_image_src.substring(category_image_src.lastIndexOf("/") + 1));
        logger.info("添加分類信息");
        boolean yn = categoryService.add(category);
        if (yn) {
            int category_id = lastIDService.selectLastID();
            logger.info("添加成功!,新增分類的ID值為:{}", category_id);
            jsonObject.put("success", true);
            jsonObject.put("category_id", category_id);
        } else {
            jsonObject.put("success", false);
            logger.warn("添加失敗!事務回滾");
            throw new RuntimeException();
        }
 
        return jsonObject.toJSONString();
    }
 
    //更新產品類型信息-ajax
    @ResponseBody
    @RequestMapping(value = "admin/category/{category_id}", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public String updateCategory(@RequestParam String category_name/* 分類名稱 */,
                                 @RequestParam String category_image_src/* 分類圖片路徑 */,
                                 @PathVariable("category_id") Integer category_id/* 分類ID */) {
        JSONObject jsonObject = new JSONObject();
        logger.info("整合分類信息");
        Category category = new Category()
                .setCategory_id(category_id)
                .setCategory_name(category_name)
                .setCategory_image_src(category_image_src.substring(category_image_src.lastIndexOf("/") + 1));
        logger.info("更新分類信息,分類ID值為:{}", category_id);
        boolean yn = categoryService.update(category);
        if (yn) {
            logger.info("更新成功!");
            jsonObject.put("success", true);
            jsonObject.put("category_id", category_id);
        } else {
            jsonObject.put("success", false);
            logger.info("更新失敗!事務回滾");
            throw new RuntimeException();
        }
 
        return jsonObject.toJSONString();
    }
 
    //按條件查詢產品類型-ajax
    @ResponseBody
    @RequestMapping(value = "admin/category/{index}/{count}", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
    public String getCategoryBySearch(@RequestParam(required = false) String category_name/* 分類名稱 */,
                                      @PathVariable Integer index/* 頁數 */,
                                      @PathVariable Integer count/* 行數 */) throws UnsupportedEncodingException {
        //移除不必要條件
        if (category_name != null) {
            //如果為非空字符串則解決中文亂碼:URLDecoder.decode(String,"UTF-8");
            category_name = "".equals(category_name) ? null : URLDecoder.decode(category_name, "UTF-8");
        }
 
        JSONObject object = new JSONObject();
        logger.info("按條件獲取第{}頁的{}條分類", index + 1, count);
        PageUtil pageUtil = new PageUtil(index, count);
        List<Category> categoryList = categoryService.getList(category_name, pageUtil);
        object.put("categoryList", JSONArray.parseArray(JSON.toJSONString(categoryList)));
        logger.info("按條件獲取分類總數量");
        Integer categoryCount = categoryService.getTotal(category_name);
        object.put("categoryCount", categoryCount);
        logger.info("獲取分頁信息");
        pageUtil.setTotal(categoryCount);
        object.put("totalPage", pageUtil.getTotalPage());
        object.put("pageUtil", pageUtil);
 
        return object.toJSONString();
    }
 
    // 上傳產品類型圖片-ajax
    @ResponseBody
    @RequestMapping(value = "admin/uploadCategoryImage", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public String uploadCategoryImage(@RequestParam MultipartFile file, HttpSession session) {
        String originalFileName = file.getOriginalFilename();
        logger.info("獲取圖片原始文件名:  {}", originalFileName);
        String extension = originalFileName.substring(originalFileName.lastIndexOf('.'));
        String fileName = UUID.randomUUID() + extension;
        String filePath = session.getServletContext().getRealPath("/") + "res/images/item/categoryPicture/" + fileName;
 
        logger.info("文件上傳路徑:{}", filePath);
        JSONObject object = new JSONObject();
        try {
            logger.info("文件上傳中...");
            file.transferTo(new File(filePath));
            logger.info("文件上傳完成");
            object.put("success", true);
            object.put("fileName", fileName);
        } catch (IOException e) {
            logger.warn("文件上傳失敗!");
            e.printStackTrace();
            object.put("success", false);
        }
 
        return object.toJSONString();
    }
}

訂單列表頁:

/**
 * 訂單列表頁
 */
@Controller
public class ForeOrderController extends BaseController {
    @Resource(name = "productService")
    private ProductService productService;
    @Resource(name = "userService")
    private UserService userService;
    @Resource(name = "productOrderItemService")
    private ProductOrderItemService productOrderItemService;
    @Resource(name = "addressService")
    private AddressService addressService;
    @Resource(name = "categoryService")
    private CategoryService categoryService;
    @Resource(name = "productImageService")
    private ProductImageService productImageService;
    @Resource(name = "productOrderService")
    private ProductOrderService productOrderService;
    @Resource(name = "reviewService")
    private ReviewService reviewService;
    @Resource(name = "lastIDService")
    private LastIDService lastIDService;
    //轉到前臺天貓-訂單列表頁
    @RequestMapping(value = "order", method = RequestMethod.GET)
    public String goToPageSimple() {
        return "redirect:/order/0/10";
    }
    @RequestMapping(value = "order/{index}/{count}", method = RequestMethod.GET)
    public String goToPage(HttpSession session, Map<String, Object> map,
                           @RequestParam(required = false) Byte status,
                           @PathVariable("index") Integer index/* 頁數 */,
                           @PathVariable("count") Integer count/* 行數*/) {
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        User user;
        if (userId != null) {
            logger.info("獲取用戶信息");
            user = userService.get(Integer.parseInt(userId.toString()));
            map.put("user", user);
        } else {
            return "redirect:/login";
        }
        Byte[] status_array = null;
        if (status != null) {
            status_array = new Byte[]{status};
        }
 
        PageUtil pageUtil = new PageUtil(index, count);
        logger.info("根據用戶ID:{}獲取訂單列表", userId);
        List<ProductOrder> productOrderList = productOrderService.getList(
                new ProductOrder().setProductOrder_user(
                        new User().setUser_id(Integer.valueOf(userId.toString()))
                ), status_array, new OrderUtil("productOrder_id", true), pageUtil
        );
 
        //訂單總數量
        Integer orderCount = 0;
        if (productOrderList.size() > 0) {
            orderCount = productOrderService.getTotal(new ProductOrder().setProductOrder_user(new User().setUser_id(Integer.valueOf(userId.toString()))), status_array);
            logger.info("獲取訂單項信息及對應的產品信息");
            for (ProductOrder order : productOrderList) {
                List<ProductOrderItem> productOrderItemList = productOrderItemService.getListByOrderId(
                        order.getProductOrder_id(), null
                );
                if (productOrderItemList != null) {
                    for (ProductOrderItem productOrderItem : productOrderItemList) {
                        Integer product_id = productOrderItem.getProductOrderItem_product().getProduct_id();
                        Product product = productService.get(product_id);
                        product.setSingleProductImageList(productImageService.getList(
                                product_id, (byte) 0, new PageUtil(0, 1)
                        ));
                        productOrderItem.setProductOrderItem_product(product);
                        if (order.getProductOrder_status() == 3) {
                            productOrderItem.setIsReview(reviewService.getTotalByOrderItemId(
                                    productOrderItem.getProductOrderItem_id()) > 0
                            );
                        }
                    }
                }
                order.setProductOrderItemList(productOrderItemList);
            }
        }
        pageUtil.setTotal(orderCount);
 
        logger.info("獲取產品分類列表信息");
        List<Category> categoryList = categoryService.getList(null, new PageUtil(0, 5));
 
        map.put("pageUtil", pageUtil);
        map.put("productOrderList", productOrderList);
        map.put("categoryList", categoryList);
        map.put("status", status);
 
        logger.info("轉到前臺天貓-訂單列表頁");
        return "fore/orderListPage";
    }
 
    //轉到前臺天貓-訂單建立頁
    @RequestMapping(value = "order/create/{product_id}", method = RequestMethod.GET)
    public String goToOrderConfirmPage(@PathVariable("product_id") Integer product_id,
                                       @RequestParam(required = false, defaultValue = "1") Short product_number,
                                       Map<String, Object> map,
                                       HttpSession session,
                                       HttpServletRequest request) throws UnsupportedEncodingException {
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        User user;
        if (userId != null) {
            logger.info("獲取用戶信息");
            user = userService.get(Integer.parseInt(userId.toString()));
            map.put("user", user);
        } else {
            return "redirect:/login";
        }
        logger.info("通過產品ID獲取產品信息:{}", product_id);
        Product product = productService.get(product_id);
        if (product == null) {
            return "redirect:/";
        }
        logger.info("獲取產品的詳細信息");
        product.setProduct_category(categoryService.get(product.getProduct_category().getCategory_id()));
        product.setSingleProductImageList(productImageService.getList(product_id, (byte) 0, new PageUtil(0, 1)));
 
        logger.info("封裝訂單項對象");
        ProductOrderItem productOrderItem = new ProductOrderItem();
        productOrderItem.setProductOrderItem_product(product);
        productOrderItem.setProductOrderItem_number(product_number);
        productOrderItem.setProductOrderItem_price(product.getProduct_sale_price() * product_number);
        productOrderItem.setProductOrderItem_user(new User().setUser_id(Integer.valueOf(userId.toString())));
 
        //初始化訂單地址信息
        String addressId = "110000";
        String cityAddressId = "110100";
        String districtAddressId = "110101";
        String detailsAddress = null;
        String order_post = null;
        String order_receiver = null;
        String order_phone = null;
        Cookie[] cookies = request.getCookies();
        //如果讀取到瞭瀏覽器Cookie
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                String cookieValue = cookie.getValue();
                switch (cookieName) {
                    case "addressId":
                        addressId = cookieValue;
                        break;
                    case "cityAddressId":
                        cityAddressId = cookieValue;
                        break;
                    case "districtAddressId":
                        districtAddressId = cookieValue;
                        break;
                    case "order_post":
                        order_post = URLDecoder.decode(cookieValue, "UTF-8");
                        break;
                    case "order_receiver":
                        order_receiver = URLDecoder.decode(cookieValue, "UTF-8");
                        break;
                    case "order_phone":
                        order_phone = URLDecoder.decode(cookieValue, "UTF-8");
                        break;
                    case "detailsAddress":
                        detailsAddress = URLDecoder.decode(cookieValue, "UTF-8");
                        break;
                }
            }
        }
        logger.info("獲取省份信息");
        List<Address> addressList = addressService.getRoot();
        logger.info("獲取addressId為{}的市級地址信息", addressId);
        List<Address> cityAddress = addressService.getList(null, addressId);
        logger.info("獲取cityAddressId為{}的區級地址信息", cityAddressId);
        List<Address> districtAddress = addressService.getList(null, cityAddressId);
 
        List<ProductOrderItem> productOrderItemList = new ArrayList<>();
        productOrderItemList.add(productOrderItem);
 
        map.put("orderItemList", productOrderItemList);
        map.put("addressList", addressList);
        map.put("cityList", cityAddress);
        map.put("districtList", districtAddress);
        map.put("orderTotalPrice", productOrderItem.getProductOrderItem_price());
 
        map.put("addressId", addressId);
        map.put("cityAddressId", cityAddressId);
        map.put("districtAddressId", districtAddressId);
        map.put("order_post", order_post);
        map.put("order_receiver", order_receiver);
        map.put("order_phone", order_phone);
        map.put("detailsAddress", detailsAddress);
 
        logger.info("轉到前臺天貓-訂單建立頁");
        return "fore/productBuyPage";
    }
 
    //轉到前臺天貓-購物車訂單建立頁
    @RequestMapping(value = "order/create/byCart", method = RequestMethod.GET)
    public String goToOrderConfirmPageByCart(Map<String, Object> map,
                                             HttpSession session, HttpServletRequest request,
                                             @RequestParam(required = false) Integer[] order_item_list) throws UnsupportedEncodingException {
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        User user;
        if (userId != null) {
            logger.info("獲取用戶信息");
            user = userService.get(Integer.parseInt(userId.toString()));
            map.put("user", user);
        } else {
            return "redirect:/login";
        }
        if (order_item_list == null || order_item_list.length == 0) {
            logger.warn("用戶訂單項數組不存在,回到購物車頁");
            return "redirect:/cart";
        }
        logger.info("通過訂單項ID數組獲取訂單信息");
        List<ProductOrderItem> orderItemList = new ArrayList<>(order_item_list.length);
        for (Integer orderItem_id : order_item_list) {
            orderItemList.add(productOrderItemService.get(orderItem_id));
        }
        logger.info("------檢查訂單項合法性------");
        if (orderItemList.size() == 0) {
            logger.warn("用戶訂單項獲取失敗,回到購物車頁");
            return "redirect:/cart";
        }
        for (ProductOrderItem orderItem : orderItemList) {
            if (orderItem.getProductOrderItem_user().getUser_id() != userId) {
                logger.warn("用戶訂單項與用戶不匹配,回到購物車頁");
                return "redirect:/cart";
            }
            if (orderItem.getProductOrderItem_order() != null) {
                logger.warn("用戶訂單項不屬於購物車,回到購物車頁");
                return "redirect:/cart";
            }
        }
        logger.info("驗證通過,獲取訂單項的產品信息");
        double orderTotalPrice = 0.0;
        for (ProductOrderItem orderItem : orderItemList) {
            Product product = productService.get(orderItem.getProductOrderItem_product().getProduct_id());
            product.setProduct_category(categoryService.get(product.getProduct_category().getCategory_id()));
            product.setSingleProductImageList(productImageService.getList(product.getProduct_id(), (byte) 0, new PageUtil(0, 1)));
            orderItem.setProductOrderItem_product(product);
            orderTotalPrice += orderItem.getProductOrderItem_price();
        }
        String addressId = "110000";
        String cityAddressId = "110100";
        String districtAddressId = "110101";
        String detailsAddress = null;
        String order_post = null;
        String order_receiver = null;
        String order_phone = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String cookieName = cookie.getName();
                String cookieValue = cookie.getValue();
                switch (cookieName) {
                    case "addressId":
                        addressId = cookieValue;
                        break;
                    case "cityAddressId":
                        cityAddressId = cookieValue;
                        break;
                    case "districtAddressId":
                        districtAddressId = cookieValue;
                        break;
                    case "order_post":
                        order_post = URLDecoder.decode(cookieValue, "UTF-8");
                        break;
                    case "order_receiver":
                        order_receiver = URLDecoder.decode(cookieValue, "UTF-8");
                        break;
                    case "order_phone":
                        order_phone = URLDecoder.decode(cookieValue, "UTF-8");
                        break;
                    case "detailsAddress":
                        detailsAddress = URLDecoder.decode(cookieValue, "UTF-8");
                        break;
                }
            }
        }
        logger.info("獲取省份信息");
        List<Address> addressList = addressService.getRoot();
        logger.info("獲取addressId為{}的市級地址信息", addressId);
        List<Address> cityAddress = addressService.getList(null, addressId);
        logger.info("獲取cityAddressId為{}的區級地址信息", cityAddressId);
        List<Address> districtAddress = addressService.getList(null, cityAddressId);
 
        map.put("orderItemList", orderItemList);
        map.put("addressList", addressList);
        map.put("cityList", cityAddress);
        map.put("districtList", districtAddress);
        map.put("orderTotalPrice", orderTotalPrice);
 
        map.put("addressId", addressId);
        map.put("cityAddressId", cityAddressId);
        map.put("districtAddressId", districtAddressId);
        map.put("order_post", order_post);
        map.put("order_receiver", order_receiver);
        map.put("order_phone", order_phone);
        map.put("detailsAddress", detailsAddress);
 
        logger.info("轉到前臺天貓-訂單建立頁");
        return "fore/productBuyPage";
    }
 
    //轉到前臺天貓-訂單支付頁
    @RequestMapping(value = "order/pay/{order_code}", method = RequestMethod.GET)
    public String goToOrderPayPage(Map<String, Object> map, HttpSession session,
                                   @PathVariable("order_code") String order_code) {
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        User user;
        if (userId != null) {
            logger.info("獲取用戶信息");
            user = userService.get(Integer.parseInt(userId.toString()));
            map.put("user", user);
        } else {
            return "redirect:/login";
        }
        logger.info("------驗證訂單信息------");
        logger.info("查詢訂單是否存在");
        ProductOrder order = productOrderService.getByCode(order_code);
        if (order == null) {
            logger.warn("訂單不存在,返回訂單列表頁");
            return "redirect:/order/0/10";
        }
        logger.info("驗證訂單狀態");
        if (order.getProductOrder_status() != 0) {
            logger.warn("訂單狀態不正確,返回訂單列表頁");
            return "redirect:/order/0/10";
        }
        logger.info("驗證用戶與訂單是否一致");
        if (order.getProductOrder_user().getUser_id() != Integer.parseInt(userId.toString())) {
            logger.warn("用戶與訂單信息不一致,返回訂單列表頁");
            return "redirect:/order/0/10";
        }
        order.setProductOrderItemList(productOrderItemService.getListByOrderId(order.getProductOrder_id(), null));
 
        double orderTotalPrice = 0.00;
        if (order.getProductOrderItemList().size() == 1) {
            logger.info("獲取單訂單項的產品信息");
            ProductOrderItem productOrderItem = order.getProductOrderItemList().get(0);
            Product product = productService.get(productOrderItem.getProductOrderItem_product().getProduct_id());
            product.setProduct_category(categoryService.get(product.getProduct_category().getCategory_id()));
            productOrderItem.setProductOrderItem_product(product);
            orderTotalPrice = productOrderItem.getProductOrderItem_price();
        } else {
            for (ProductOrderItem productOrderItem : order.getProductOrderItemList()) {
                orderTotalPrice += productOrderItem.getProductOrderItem_price();
            }
        }
        logger.info("訂單總金額為:{}元", orderTotalPrice);
 
        map.put("productOrder", order);
        map.put("orderTotalPrice", orderTotalPrice);
 
        logger.info("轉到前臺天貓-訂單支付頁");
        return "fore/productPayPage";
    }
 
    //轉到前臺天貓-訂單支付成功頁
    @RequestMapping(value = "order/pay/success/{order_code}", method = RequestMethod.GET)
    public String goToOrderPaySuccessPage(Map<String, Object> map, HttpSession session,
                                          @PathVariable("order_code") String order_code) {
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        User user;
        if (userId != null) {
            logger.info("獲取用戶信息");
            user = userService.get(Integer.parseInt(userId.toString()));
            map.put("user", user);
        } else {
            return "redirect:/login";
        }
        logger.info("------驗證訂單信息------");
        logger.info("查詢訂單是否存在");
        ProductOrder order = productOrderService.getByCode(order_code);
        if (order == null) {
            logger.warn("訂單不存在,返回訂單列表頁");
            return "redirect:/order/0/10";
        }
        logger.info("驗證訂單狀態");
        if (order.getProductOrder_status() != 1) {
            logger.warn("訂單狀態不正確,返回訂單列表頁");
            return "redirect:/order/0/10";
        }
        logger.info("驗證用戶與訂單是否一致");
        if (order.getProductOrder_user().getUser_id() != Integer.parseInt(userId.toString())) {
            logger.warn("用戶與訂單信息不一致,返回訂單列表頁");
            return "redirect:/order/0/10";
        }
        order.setProductOrderItemList(productOrderItemService.getListByOrderId(order.getProductOrder_id(), null));
 
        double orderTotalPrice = 0.00;
        if (order.getProductOrderItemList().size() == 1) {
            logger.info("獲取單訂單項的產品信息");
            ProductOrderItem productOrderItem = order.getProductOrderItemList().get(0);
//            Product pro = pro.setProduct_id(productOrderItem.getProductOrderItem_product().getProduct_id());
            Product pro = productService.get(productOrderItem.getProductOrderItem_product().getProduct_id());
            System.out.println(pro.getProduct_stock_count());
            System.out.println(productOrderItem.getProductOrderItem_number());
            pro.setProduct_stock_count(pro.getProduct_stock_count()-productOrderItem.getProductOrderItem_number());
//            此處減庫存
            productService.update(pro);
            orderTotalPrice = productOrderItem.getProductOrderItem_price();
        } else {
            for (ProductOrderItem productOrderItem : order.getProductOrderItemList()) {
            	   Product pro = productService.get(productOrderItem.getProductOrderItem_product().getProduct_id());
                   System.out.println(pro.getProduct_stock_count());
                   System.out.println(productOrderItem.getProductOrderItem_number());
                   pro.setProduct_stock_count(pro.getProduct_stock_count()-productOrderItem.getProductOrderItem_number());
//                   此處減庫存
                   productService.update(pro);
                orderTotalPrice += productOrderItem.getProductOrderItem_price();
            }
        }
        logger.info("訂單總金額為:{}元", orderTotalPrice);
 
        logger.info("獲取訂單詳情-地址信息");
        Address address = addressService.get(order.getProductOrder_address().getAddress_areaId());
        Stack<String> addressStack = new Stack<>();
        //詳細地址
        addressStack.push(order.getProductOrder_detail_address());
        //最後一級地址
        addressStack.push(address.getAddress_name() + " ");
        //如果不是第一級地址
        while (!address.getAddress_areaId().equals(address.getAddress_regionId().getAddress_areaId())) {
            address = addressService.get(address.getAddress_regionId().getAddress_areaId());
            addressStack.push(address.getAddress_name() + " ");
        }
        StringBuilder builder = new StringBuilder();
        while (!addressStack.empty()) {
            builder.append(addressStack.pop());
        }
        logger.info("訂單地址字符串:{}", builder);
        order.setProductOrder_detail_address(builder.toString());
 
        map.put("productOrder", order);
        map.put("orderTotalPrice", orderTotalPrice);
 
        logger.info("轉到前臺天貓-訂單支付成功頁");
        return "fore/productPaySuccessPage";
    }
 
    //轉到前臺天貓-訂單確認頁
    @RequestMapping(value = "order/confirm/{order_code}", method = RequestMethod.GET)
    public String goToOrderConfirmPage(Map<String, Object> map, HttpSession session,
                                       @PathVariable("order_code") String order_code) {
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        User user;
        if (userId != null) {
            logger.info("獲取用戶信息");
            user = userService.get(Integer.parseInt(userId.toString()));
            map.put("user", user);
        } else {
            return "redirect:/login";
        }
        logger.info("------驗證訂單信息------");
        logger.info("查詢訂單是否存在");
        ProductOrder order = productOrderService.getByCode(order_code);
        if (order == null) {
            logger.warn("訂單不存在,返回訂單列表頁");
            return "redirect:/order/0/10";
        }
        logger.info("驗證訂單狀態");
        if (order.getProductOrder_status() != 2) {
            logger.warn("訂單狀態不正確,返回訂單列表頁");
            return "redirect:/order/0/10";
        }
        logger.info("驗證用戶與訂單是否一致");
        if (order.getProductOrder_user().getUser_id() != Integer.parseInt(userId.toString())) {
            logger.warn("用戶與訂單信息不一致,返回訂單列表頁");
            return "redirect:/order/0/10";
        }
        order.setProductOrderItemList(productOrderItemService.getListByOrderId(order.getProductOrder_id(), null));
 
        double orderTotalPrice = 0.00;
        if (order.getProductOrderItemList().size() == 1) {
            logger.info("獲取單訂單項的產品信息");
            ProductOrderItem productOrderItem = order.getProductOrderItemList().get(0);
            Integer product_id = productOrderItem.getProductOrderItem_product().getProduct_id();
            Product product = productService.get(product_id);
            product.setSingleProductImageList(productImageService.getList(product_id, (byte) 0, new PageUtil(0, 1)));
            productOrderItem.setProductOrderItem_product(product);
            orderTotalPrice = productOrderItem.getProductOrderItem_price();
        } else {
            logger.info("獲取多訂單項的產品信息");
            for (ProductOrderItem productOrderItem : order.getProductOrderItemList()) {
                Integer product_id = productOrderItem.getProductOrderItem_product().getProduct_id();
                Product product = productService.get(product_id);
                product.setSingleProductImageList(productImageService.getList(product_id, (byte) 0, new PageUtil(0, 1)));
                productOrderItem.setProductOrderItem_product(product);
                orderTotalPrice += productOrderItem.getProductOrderItem_price();
            }
        }
        logger.info("訂單總金額為:{}元", orderTotalPrice);
 
        map.put("productOrder", order);
        map.put("orderTotalPrice", orderTotalPrice);
 
        logger.info("轉到前臺天貓-訂單確認頁");
        return "fore/orderConfirmPage";
    }
 
    //轉到前臺天貓-訂單完成頁
    @RequestMapping(value = "order/success/{order_code}", method = RequestMethod.GET)
    public String goToOrderSuccessPage(Map<String, Object> map, HttpSession session,
                                       @PathVariable("order_code") String order_code) {
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        User user;
        if (userId != null) {
            logger.info("獲取用戶信息");
            user = userService.get(Integer.parseInt(userId.toString()));
            map.put("user", user);
        } else {
            return "redirect:/login";
        }
        logger.info("------驗證訂單信息------");
        logger.info("查詢訂單是否存在");
        ProductOrder order = productOrderService.getByCode(order_code);
        if (order == null) {
            logger.warn("訂單不存在,返回訂單列表頁");
            return "redirect:/order/0/10";
        }
        logger.info("驗證訂單狀態");
        if (order.getProductOrder_status() != 3) {
            logger.warn("訂單狀態不正確,返回訂單列表頁");
            return "redirect:/order/0/10";
        }
        logger.info("驗證用戶與訂單是否一致");
        if (order.getProductOrder_user().getUser_id() != Integer.parseInt(userId.toString())) {
            logger.warn("用戶與訂單信息不一致,返回訂單列表頁");
            return "redirect:/order/0/10";
        }
        logger.info("獲取訂單中訂單項數量");
        Integer count = productOrderItemService.getTotalByOrderId(order.getProductOrder_id());
        Product product = null;
        if (count == 1) {
            logger.info("獲取訂單中的唯一訂單項");
            ProductOrderItem productOrderItem = productOrderItemService.getListByOrderId(order.getProductOrder_id(), new PageUtil(0, 1)).get(0);
            if (productOrderItem != null) {
                logger.info("獲取訂單項評論數量");
                count = reviewService.getTotalByOrderItemId(productOrderItem.getProductOrderItem_id());
                if (count == 0) {
                    logger.info("獲取訂單項產品信息");
                    product = productService.get(productOrderItem.getProductOrderItem_product().getProduct_id());
                    if (product != null) {
                        product.setSingleProductImageList(productImageService.getList(product.getProduct_id(), (byte) 0, new PageUtil(0, 1)));
                    }
                }
            }
            map.put("orderItem", productOrderItem);
        }
 
        map.put("product", product);
 
        logger.info("轉到前臺天貓-訂單完成頁");
        return "fore/orderSuccessPage";
    }
 
    //轉到前臺天貓-購物車頁
    @RequestMapping(value = "cart", method = RequestMethod.GET)
    public String goToCartPage(Map<String, Object> map, HttpSession session) {
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        User user;
        if (userId != null) {
            logger.info("獲取用戶信息");
            user = userService.get(Integer.parseInt(userId.toString()));
            map.put("user", user);
        } else {
            return "redirect:/login";
        }
        logger.info("獲取用戶購物車信息");
        List<ProductOrderItem> orderItemList = productOrderItemService.getListByUserId(Integer.valueOf(userId.toString()), null);
        Integer orderItemTotal = 0;
        if (orderItemList.size() > 0) {
            logger.info("獲取用戶購物車的商品總數");
            orderItemTotal = productOrderItemService.getTotalByUserId(Integer.valueOf(userId.toString()));
            logger.info("獲取用戶購物車內的商品信息");
            for (ProductOrderItem orderItem : orderItemList) {
                Integer product_id = orderItem.getProductOrderItem_product().getProduct_id();
                Product product = productService.get(product_id);
                product.setSingleProductImageList(productImageService.getList(product_id, (byte) 0, null));
                product.setProduct_category(categoryService.get(product.getProduct_category().getCategory_id()));
                orderItem.setProductOrderItem_product(product);
            }
        }
        map.put("orderItemList", orderItemList);
        map.put("orderItemTotal", orderItemTotal);
 
        logger.info("轉到前臺天貓-購物車頁");
        return "fore/productBuyCarPage";
    }
 
    //更新訂單信息為已支付,待發貨-ajax
    @ResponseBody
    @RequestMapping(value = "order/pay/{order_code}", method = RequestMethod.PUT)
    public String orderPay(HttpSession session, @PathVariable("order_code") String order_code) {
        JSONObject object = new JSONObject();
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        if (userId == null) {
            object.put("success", false);
            object.put("url", "/login");
            return object.toJSONString();
        }
        logger.info("------驗證訂單信息------");
        logger.info("查詢訂單是否存在");
        ProductOrder order = productOrderService.getByCode(order_code);
        if (order == null) {
            logger.warn("訂單不存在,返回訂單列表頁");
            object.put("success", false);
            object.put("url", "/order/0/10");
            return object.toJSONString();
        }
        logger.info("驗證訂單狀態");
        if (order.getProductOrder_status() != 0) {
            logger.warn("訂單狀態不正確,返回訂單列表頁");
            object.put("success", false);
            object.put("url", "/order/0/10");
            return object.toJSONString();
        }
        logger.info("驗證用戶與訂單是否一致");
        if (order.getProductOrder_user().getUser_id() != Integer.parseInt(userId.toString())) {
            logger.warn("用戶與訂單信息不一致,返回訂單列表頁");
            object.put("success", false);
            object.put("url", "/order/0/10");
            return object.toJSONString();
        }
        order.setProductOrderItemList(productOrderItemService.getListByOrderId(order.getProductOrder_id(), null));
 
        double orderTotalPrice = 0.00;
        if (order.getProductOrderItemList().size() == 1) {
            logger.info("獲取單訂單項的產品信息");
            ProductOrderItem productOrderItem = order.getProductOrderItemList().get(0);
            Product product = productService.get(productOrderItem.getProductOrderItem_product().getProduct_id());
            product.setProduct_category(categoryService.get(product.getProduct_category().getCategory_id()));
            productOrderItem.setProductOrderItem_product(product);
            orderTotalPrice = productOrderItem.getProductOrderItem_price();
            logger.info("更新產品銷量信息");
            Product updateProduct = new Product()
                    .setProduct_id(product.getProduct_id())
                    .setProduct_sale_count(product.getProduct_sale_count() + productOrderItem.getProductOrderItem_number());
            logger.info("更新產品信息,產品ID值為:{}", product.getProduct_id());
            boolean yn = productService.update(updateProduct);
            if (!yn) {
                logger.info("產品銷量信息更新失敗!事務回滾");
                object.put("success", false);
                throw new RuntimeException();
            }
            logger.info("產品銷量信息更新成功!");
        } else {
            for (ProductOrderItem productOrderItem : order.getProductOrderItemList()) {
                Product product = productService.get(productOrderItem.getProductOrderItem_product().getProduct_id());
                logger.info("更新產品銷量信息");
                Product updateProduct = new Product()
                        .setProduct_id(product.getProduct_id())
                        .setProduct_sale_count(product.getProduct_sale_count() + productOrderItem.getProductOrderItem_number());
                logger.info("更新產品信息,產品ID值為:{}", product.getProduct_id());
                boolean yn = productService.update(updateProduct);
                if (!yn) {
                    logger.info("產品銷量信息更新失敗!事務回滾");
                    object.put("success", false);
                    throw new RuntimeException();
                }
                logger.info("產品銷量信息更新成功!");
                orderTotalPrice += productOrderItem.getProductOrderItem_price();
            }
        }
        logger.info("總共支付金額為:{}元", orderTotalPrice);
        logger.info("更新訂單信息");
        ProductOrder productOrder = new ProductOrder()
                .setProductOrder_id(order.getProductOrder_id())
                .setProductOrder_pay_date(new Date())
                .setProductOrder_status((byte) 1);
 
        boolean yn = productOrderService.update(productOrder);
        if (yn) {
            object.put("success", true);
            object.put("url", "/order/pay/success/" + order_code);
        } else {
            object.put("success", false);
            object.put("url", "/order/0/10");
        }
        return object.toJSONString();
    }
 
    //更新訂單信息為已發貨,待確認-ajax
    @RequestMapping(value = "order/delivery/{order_code}", method = RequestMethod.GET)
    public String orderDelivery(HttpSession session, @PathVariable("order_code") String order_code) {
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        if (userId == null) {
            return "redirect:/order/0/10";
        }
        logger.info("------驗證訂單信息------");
        logger.info("查詢訂單是否存在");
        ProductOrder order = productOrderService.getByCode(order_code);
        if (order == null) {
            logger.warn("訂單不存在,返回訂單列表頁");
            return "redirect:/order/0/10";
        }
        logger.info("驗證訂單狀態");
        if (order.getProductOrder_status() != 1) {
            logger.warn("訂單狀態不正確,返回訂單列表頁");
            return "redirect:/order/0/10";
        }
        logger.info("驗證用戶與訂單是否一致");
        if (order.getProductOrder_user().getUser_id() != Integer.parseInt(userId.toString())) {
            logger.warn("用戶與訂單信息不一致,返回訂單列表頁");
            return "redirect:/order/0/10";
        }
        logger.info("更新訂單信息");
        ProductOrder productOrder = new ProductOrder()
                .setProductOrder_id(order.getProductOrder_id())
                .setProductOrder_delivery_date(new Date())
                .setProductOrder_status((byte) 2);
 
        productOrderService.update(productOrder);
 
        return "redirect:/order/0/10";
    }
 
    //更新訂單信息為交易成功-ajax
    @ResponseBody
    @RequestMapping(value = "order/success/{order_code}", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public String orderSuccess(HttpSession session, @PathVariable("order_code") String order_code) {
        JSONObject object = new JSONObject();
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        if (userId == null) {
            object.put("success", false);
            object.put("url", "/login");
            return object.toJSONString();
        }
        logger.info("------驗證訂單信息------");
        logger.info("查詢訂單是否存在");
        ProductOrder order = productOrderService.getByCode(order_code);
        if (order == null) {
            logger.warn("訂單不存在,返回訂單列表頁");
            object.put("success", false);
            object.put("url", "/order/0/10");
            return object.toJSONString();
        }
        logger.info("驗證訂單狀態");
        if (order.getProductOrder_status() != 2) {
            logger.warn("訂單狀態不正確,返回訂單列表頁");
            object.put("success", false);
            object.put("url", "/order/0/10");
            return object.toJSONString();
        }
        logger.info("驗證用戶與訂單是否一致");
        if (order.getProductOrder_user().getUser_id() != Integer.parseInt(userId.toString())) {
            logger.warn("用戶與訂單信息不一致,返回訂單列表頁");
            object.put("success", false);
            object.put("url", "/order/0/10");
            return object.toJSONString();
        }
        logger.info("更新訂單信息");
        ProductOrder productOrder = new ProductOrder()
                .setProductOrder_id(order.getProductOrder_id())
                .setProductOrder_status((byte) 3)
                .setProductOrder_confirm_date(new Date());
 
        boolean yn = productOrderService.update(productOrder);
        if (yn) {
            object.put("success", true);
        } else {
            object.put("success", false);
        }
        return object.toJSONString();
    }
 
    //更新訂單信息為交易關閉-ajax
    @ResponseBody
    @RequestMapping(value = "order/close/{order_code}", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public String orderClose(HttpSession session, @PathVariable("order_code") String order_code) {
        JSONObject object = new JSONObject();
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        if (userId == null) {
            object.put("success", false);
            object.put("url", "/login");
            return object.toJSONString();
        }
        logger.info("------驗證訂單信息------");
        logger.info("查詢訂單是否存在");
        ProductOrder order = productOrderService.getByCode(order_code);
        if (order == null) {
            logger.warn("訂單不存在,返回訂單列表頁");
            object.put("success", false);
            object.put("url", "/order/0/10");
            return object.toJSONString();
        }
        logger.info("驗證訂單狀態");
        if (order.getProductOrder_status() != 0) {
            logger.warn("訂單狀態不正確,返回訂單列表頁");
            object.put("success", false);
            object.put("url", "/order/0/10");
            return object.toJSONString();
        }
        logger.info("驗證用戶與訂單是否一致");
        if (order.getProductOrder_user().getUser_id() != Integer.parseInt(userId.toString())) {
            logger.warn("用戶與訂單信息不一致,返回訂單列表頁");
            object.put("success", false);
            object.put("url", "/order/0/10");
            return object.toJSONString();
        }
        logger.info("更新訂單信息");
        ProductOrder productOrder = new ProductOrder()
                .setProductOrder_id(order.getProductOrder_id())
                .setProductOrder_status((byte) 4);
 
        boolean yn = productOrderService.update(productOrder);
        if (yn) {
            object.put("success", true);
        } else {
            object.put("success", false);
        }
        return object.toJSONString();
    }
 
    //更新購物車訂單項數量-ajax
    @ResponseBody
    @RequestMapping(value = "orderItem", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
    public String updateOrderItem(HttpSession session, Map<String, Object> map, HttpServletResponse response,
                                  @RequestParam String orderItemMap) {
        JSONObject object = new JSONObject();
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        if (userId == null) {
            object.put("success", false);
            return object.toJSONString();
        }
 
        JSONObject orderItemString = JSON.parseObject(orderItemMap);
        Set<String> orderItemIDSet = orderItemString.keySet();
        if (orderItemIDSet.size() > 0) {
            logger.info("更新產品訂單項數量");
            for (String key : orderItemIDSet) {
                ProductOrderItem productOrderItem = productOrderItemService.get(Integer.valueOf(key));
                if (productOrderItem == null || !productOrderItem.getProductOrderItem_user().getUser_id().equals(userId)) {
                    logger.warn("訂單項為空或用戶狀態不一致!");
                    object.put("success", false);
                    return object.toJSONString();
                }
                if (productOrderItem.getProductOrderItem_order() != null) {
                    logger.warn("用戶訂單項不屬於購物車,回到購物車頁");
                    return "redirect:/cart";
                }
                Short number = Short.valueOf(orderItemString.getString(key));
                if (number <= 0 || number > 500) {
                    logger.warn("訂單項產品數量不合法!");
                    object.put("success", false);
                    return object.toJSONString();
                }
                double price = productOrderItem.getProductOrderItem_price() / productOrderItem.getProductOrderItem_number();
                Boolean yn = productOrderItemService.update(new ProductOrderItem().setProductOrderItem_id(Integer.valueOf(key)).setProductOrderItem_number(number).setProductOrderItem_price(number * price));
                if (!yn) {
                    throw new RuntimeException();
                }
            }
            Object[] orderItemIDArray = orderItemIDSet.toArray();
            object.put("success", true);
            object.put("orderItemIDArray", orderItemIDArray);
            return object.toJSONString();
        } else {
            logger.warn("無訂單項可以處理");
            object.put("success", false);
            return object.toJSONString();
        }
    }
 
    //創建新訂單-單訂單項-ajax
    @ResponseBody
    @RequestMapping(value = "order", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public String createOrderByOne(HttpSession session, Map<String, Object> map, HttpServletResponse response,
                                   @RequestParam String addressId,
                                   @RequestParam String cityAddressId,
                                   @RequestParam String districtAddressId,
                                   @RequestParam String productOrder_detail_address,
                                   @RequestParam String productOrder_post,
                                   @RequestParam String productOrder_receiver,
                                   @RequestParam String productOrder_mobile,
                                   @RequestParam String userMessage,
                                   @RequestParam Integer orderItem_product_id,
                                   @RequestParam Short orderItem_number) throws UnsupportedEncodingException {
        JSONObject object = new JSONObject();
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        if (userId == null) {
            object.put("success", false);
            object.put("url", "/login");
            return object.toJSONString();
        }
        Product product = productService.get(orderItem_product_id);
       
        if (product == null) {
            object.put("success", false);
            object.put("url", "/");
            return object.toJSONString();
        }
    	if(product.getProduct_stock_count()<orderItem_number) {
    		object.put("success", false);
            object.put("url", "/not");
            return object.toJSONString();
        }
        logger.info("將收貨地址等相關信息存入Cookie中,便於下次使用");
        Cookie[] cookies = new Cookie[]{
                new Cookie("addressId", addressId),
                new Cookie("cityAddressId", cityAddressId),
                new Cookie("districtAddressId", districtAddressId),
                new Cookie("order_post", URLEncoder.encode(productOrder_post, "UTF-8")),
                new Cookie("order_receiver", URLEncoder.encode(productOrder_receiver, "UTF-8")),
                new Cookie("order_phone", URLEncoder.encode(productOrder_mobile, "UTF-8")),
                new Cookie("detailsAddress", URLEncoder.encode(productOrder_detail_address, "UTF-8"))
        };
        int maxAge = 60 * 60 * 24 * 365;
        for(Cookie cookie : cookies){
            //設置過期時間為一年
            cookie.setMaxAge(maxAge);
            //存儲Cookie
            response.addCookie(cookie);
        }
        StringBuffer productOrder_code = new StringBuffer()
                .append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()))
                .append(0)
                .append(userId);
        logger.info("生成的訂單號為:{}", productOrder_code);
        logger.info("整合訂單對象");
        ProductOrder productOrder = new ProductOrder()
                .setProductOrder_status((byte) 0)
                .setProductOrder_address(new Address().setAddress_areaId(districtAddressId))
                .setProductOrder_post(productOrder_post)
                .setProductOrder_user(new User().setUser_id(Integer.valueOf(userId.toString())))
                .setProductOrder_mobile(productOrder_mobile)
                .setProductOrder_receiver(productOrder_receiver)
                .setProductOrder_detail_address(productOrder_detail_address)
                .setProductOrder_pay_date(new Date())
                .setProductOrder_code(productOrder_code.toString());
        Boolean yn = productOrderService.add(productOrder);
        if (!yn) {
            throw new RuntimeException();
        }
        Integer order_id = lastIDService.selectLastID();
        logger.info("整合訂單項對象");
        ProductOrderItem productOrderItem = new ProductOrderItem()
                .setProductOrderItem_user(new User().setUser_id(Integer.valueOf(userId.toString())))
                .setProductOrderItem_product(productService.get(orderItem_product_id))
                .setProductOrderItem_number(orderItem_number)
                .setProductOrderItem_price(product.getProduct_sale_price() * orderItem_number)
                .setProductOrderItem_userMessage(userMessage)
                .setProductOrderItem_order(new ProductOrder().setProductOrder_id(order_id));
        yn = productOrderItemService.add(productOrderItem);
        if (!yn) {
            throw new RuntimeException();
        }
 
        object.put("success", true);
        object.put("url", "/order/pay/" + productOrder.getProductOrder_code());
        return object.toJSONString();
    }
 
    //創建新訂單-多訂單項-ajax
    @ResponseBody
    @RequestMapping(value = "order/list", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public String createOrderByList(HttpSession session, Map<String, Object> map, HttpServletResponse response,
                                    @RequestParam String addressId,
                                    @RequestParam String cityAddressId,
                                    @RequestParam String districtAddressId,
                                    @RequestParam String productOrder_detail_address,
                                    @RequestParam String productOrder_post,
                                    @RequestParam String productOrder_receiver,
                                    @RequestParam String productOrder_mobile,
                                    @RequestParam String orderItemJSON) throws UnsupportedEncodingException {
        JSONObject object = new JSONObject();
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        if (userId == null) {
            object.put("success", false);
            object.put("url", "/login");
            return object.toJSONString();
        }
        JSONObject orderItemMap = JSONObject.parseObject(orderItemJSON);
        Set<String> orderItem_id = orderItemMap.keySet();
        List<ProductOrderItem> productOrderItemList = new ArrayList<>(3);
        if (orderItem_id.size() > 0) {
            for (String id : orderItem_id) {
                ProductOrderItem orderItem = productOrderItemService.get(Integer.valueOf(id));
                if (orderItem == null || !orderItem.getProductOrderItem_user().getUser_id().equals(userId)) {
                    logger.warn("訂單項為空或用戶狀態不一致!");
                    object.put("success", false);
                    object.put("url", "/cart");
                    return object.toJSONString();
                }
                if(orderItem.getProductOrderItem_product().getProduct_stock_count()<orderItem.getProductOrderItem_number()) {
            		object.put("success", false);
                    object.put("url", "/not");
                    return object.toJSONString();
                }
                if (orderItem.getProductOrderItem_order() != null) {
                    logger.warn("用戶訂單項不屬於購物車,回到購物車頁");
                    object.put("success", false);
                    object.put("url", "/cart");
                    return object.toJSONString();
                }
                boolean yn = productOrderItemService.update(new ProductOrderItem().setProductOrderItem_id(Integer.valueOf(id)).setProductOrderItem_userMessage(orderItemMap.getString(id)));
                if (!yn) {
                    throw new RuntimeException();
                }
                orderItem.setProductOrderItem_product(productService.get(orderItem.getProductOrderItem_product().getProduct_id()));
                productOrderItemList.add(orderItem);
            }
        } else {
            object.put("success", false);
            object.put("url", "/cart");
            return object.toJSONString();
        }
        logger.info("將收貨地址等相關信息存入Cookie中,便於下次使用");
        Cookie[] cookies = new Cookie[]{
                new Cookie("addressId", addressId),
                new Cookie("cityAddressId", cityAddressId),
                new Cookie("districtAddressId", districtAddressId),
                new Cookie("order_post", URLEncoder.encode(productOrder_post, "UTF-8")),
                new Cookie("order_receiver", URLEncoder.encode(productOrder_receiver, "UTF-8")),
                new Cookie("order_phone", URLEncoder.encode(productOrder_mobile, "UTF-8")),
                new Cookie("detailsAddress", URLEncoder.encode(productOrder_detail_address, "UTF-8"))
        };
        int maxAge = 60 * 60 * 24 * 365;
        for(Cookie cookie : cookies){
            //設置過期時間為一年
            cookie.setMaxAge(maxAge);
            //存儲Cookie
            response.addCookie(cookie);
        }
        StringBuffer productOrder_code = new StringBuffer()
                .append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()))
                .append(0)
                .append(userId);
        logger.info("生成的訂單號為:{}", productOrder_code);
        logger.info("整合訂單對象");
        ProductOrder productOrder = new ProductOrder()
                .setProductOrder_status((byte) 0)
                .setProductOrder_address(new Address().setAddress_areaId(districtAddressId))
                .setProductOrder_post(productOrder_post)
                .setProductOrder_user(new User().setUser_id(Integer.valueOf(userId.toString())))
                .setProductOrder_mobile(productOrder_mobile)
                .setProductOrder_receiver(productOrder_receiver)
                .setProductOrder_detail_address(productOrder_detail_address)
                .setProductOrder_pay_date(new Date())
                .setProductOrder_code(productOrder_code.toString());
        Boolean yn = productOrderService.add(productOrder);
        if (!yn) {
            throw new RuntimeException();
        }
        Integer order_id = lastIDService.selectLastID();
        logger.info("整合訂單項對象");
        for (ProductOrderItem orderItem : productOrderItemList) {
            orderItem.setProductOrderItem_order(new ProductOrder().setProductOrder_id(order_id));
            yn = productOrderItemService.update(orderItem);
        }
        if (!yn) {
            throw new RuntimeException();
        }
 
        object.put("success", true);
        object.put("url", "/order/pay/" + productOrder.getProductOrder_code());
        return object.toJSONString();
    }
 
    //創建訂單項-購物車-ajax
    @ResponseBody
    @RequestMapping(value = "orderItem/create/{product_id}", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public String createOrderItem(@PathVariable("product_id") Integer product_id,
                                  @RequestParam(required = false, defaultValue = "1") Short product_number,
                                  HttpSession session,
                                  HttpServletRequest request) {
        JSONObject object = new JSONObject();
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        if (userId == null) {
            object.put("url", "/login");
            object.put("success", false);
            return object.toJSONString();
        }
 
        logger.info("通過產品ID獲取產品信息:{}", product_id);
        Product product = productService.get(product_id);
        if (product == null) {
            object.put("url", "/login");
            object.put("success", false);
            return object.toJSONString();
        }
 
        ProductOrderItem productOrderItem = new ProductOrderItem();
        logger.info("檢查用戶的購物車項");
        List<ProductOrderItem> orderItemList = productOrderItemService.getListByUserId(Integer.valueOf(userId.toString()), null);
        for (ProductOrderItem orderItem : orderItemList) {
            if (orderItem.getProductOrderItem_product().getProduct_id().equals(product_id)) {
                logger.info("找到已有的產品,進行數量追加");
                int number = orderItem.getProductOrderItem_number();
                number += 1;
                productOrderItem.setProductOrderItem_id(orderItem.getProductOrderItem_id());
                productOrderItem.setProductOrderItem_number((short) number);
                productOrderItem.setProductOrderItem_price(number * product.getProduct_sale_price());
                boolean yn = productOrderItemService.update(productOrderItem);
                if (yn) {
                    object.put("success", true);
                } else {
                    object.put("success", false);
                }
                return object.toJSONString();
            }
        }
        logger.info("封裝訂單項對象");
        productOrderItem.setProductOrderItem_product(product);
        productOrderItem.setProductOrderItem_number(product_number);
        productOrderItem.setProductOrderItem_price(product.getProduct_sale_price() * product_number);
        productOrderItem.setProductOrderItem_user(new User().setUser_id(Integer.valueOf(userId.toString())));
        boolean yn = productOrderItemService.add(productOrderItem);
        if (yn) {
            object.put("success", true);
        } else {
            object.put("success", false);
        }
        return object.toJSONString();
    }
 
    //刪除訂單項-購物車-ajax
    @ResponseBody
    @RequestMapping(value = "orderItem/{orderItem_id}", method = RequestMethod.DELETE, produces = "application/json;charset=utf-8")
    public String deleteOrderItem(@PathVariable("orderItem_id") Integer orderItem_id,
                                  HttpSession session,
                                  HttpServletRequest request) {
        JSONObject object = new JSONObject();
        logger.info("檢查用戶是否登錄");
        Object userId = checkUser(session);
        if (userId == null) {
            object.put("url", "/login");
            object.put("success", false);
            return object.toJSONString();
        }
        logger.info("檢查用戶的購物車項");
        List<ProductOrderItem> orderItemList = productOrderItemService.getListByUserId(Integer.valueOf(userId.toString()), null);
        boolean isMine = false;
        for (ProductOrderItem orderItem : orderItemList) {
            logger.info("找到匹配的購物車項");
            if (orderItem.getProductOrderItem_id().equals(orderItem_id)) {
                isMine = true;
                break;
            }
        }
        if (isMine) {
            logger.info("刪除訂單項信息");
            boolean yn = productOrderItemService.deleteList(new Integer[]{orderItem_id});
            if (yn) {
                object.put("success", true);
            } else {
                object.put("success", false);
            }
        } else {
            object.put("success", false);
        }
        return object.toJSONString();
    }
}

用戶登錄頁:

/**
 * 登陸頁
 */
@Controller
public class ForeLoginController extends BaseController {
    @Resource(name = "userService")
    private UserService userService;
 
    //轉到前臺天貓-登錄頁
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String goToPage(HttpSession session, Map<String, Object> map) {
        logger.info("轉到前臺天貓-登錄頁");
        return "fore/loginPage";
    }
    @RequestMapping(value = "not", method = RequestMethod.GET)
    public String not(HttpSession session, Map<String, Object> map) {
        logger.info("轉到cuwu頁");
        return "fore/not";
    }
    //登陸驗證-ajax
    @ResponseBody
    @RequestMapping(value = "login/doLogin", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
    public String checkLogin(HttpSession session, @RequestParam String username, @RequestParam String password) {
        logger.info("用戶驗證登錄");
        User user = userService.login(username, password);
 
        JSONObject jsonObject = new JSONObject();
        if (user == null) {
            logger.info("登錄驗證失敗");
            jsonObject.put("success", false);
        } else {
            logger.info("登錄驗證成功,用戶ID傳入會話");
            session.setAttribute("userId", user.getUser_id());
            jsonObject.put("success", true);
        }
        return jsonObject.toJSONString();
    }
 
    //退出當前賬號
    @RequestMapping(value = "login/logout", method = RequestMethod.GET)
    public String logout(HttpSession session) {
        Object o = session.getAttribute("userId");
        if (o != null) {
            session.removeAttribute("userId");
            session.invalidate();
            logger.info("登錄信息已清除,返回用戶登錄頁");
        }
        return "redirect:/login";
    }
}

到此這篇關於Java畢業設計實戰項目之在線服裝銷售商城系統的實現流程的文章就介紹到這瞭,更多相關Java 服裝商城系統內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: