Java實(shí)戰(zhàn)之仿天貓商城系統(tǒng)的實(shí)現(xiàn)
一、項(xiàng)目介紹
迷你天貓商城是一個(gè)基于SSM框架的綜合性B2C電商平臺(tái),需求設(shè)計(jì)主要參考天貓商城的購(gòu)物流程:用戶(hù)從注冊(cè)開(kāi)始,到完成登錄,瀏覽商品,加入購(gòu)物車(chē),進(jìn)行下單,確認(rèn)收貨,評(píng)價(jià)等一系列操作。
作為模擬天貓商城系統(tǒng)的核心組成部分之一,采用SSM框架的天貓數(shù)據(jù)管理后臺(tái)包含商品管理,訂單管理,類(lèi)別管理,用戶(hù)管理和交易額統(tǒng)計(jì)等模塊,實(shí)現(xiàn)了對(duì)整個(gè)商城的一站式管理和維護(hù)。
二、項(xiàng)目運(yùn)行
環(huán)境配置: Jdk1.8 + Tomcat8.5 + mysql + Eclispe (IntelliJ IDEA,Eclispe,MyEclispe,Sts 都支持)
項(xiàng)目技術(shù): JSP + Springboot + SpringMVC + Spring +MyBatis + css + JavaScript + JQuery + Ajax + layui+ maven等等。
三、效果圖







四、核心代碼
權(quán)限基礎(chǔ)控制層
/**
* 基控制器
*/
public class BaseController {
//log4j
protected Logger logger = LogManager.getLogger(LogManager.ROOT_LOGGER_NAME);
//檢查管理員權(quán)限
protected Object checkAdmin(HttpSession session){
Object o = session.getAttribute("adminId");
if(o==null){
logger.info("無(wú)管理權(quán)限,返回管理員登陸頁(yè)");
return null;
}
logger.info("權(quán)限驗(yàn)證成功,管理員ID:{}",o);
return o;
}
//檢查用戶(hù)是否登錄
protected Object checkUser(HttpSession session){
Object o = session.getAttribute("userId");
if(o==null){
logger.info("用戶(hù)未登錄");
return null;
}
logger.info("用戶(hù)已登錄,用戶(hù)ID:{}", o);
return o;
}
}用戶(hù)信息操作控制層
@Controller
public class ForeUserController extends BaseController{
@Autowired
private AddressService addressService;
@Autowired
private UserService userService;
//轉(zhuǎn)到前臺(tái)天貓-用戶(hù)詳情頁(yè)
@RequestMapping(value = "userDetails", method = RequestMethod.GET)
public String goToUserDetail(HttpSession session, Map<String,Object> map){
logger.info("檢查用戶(hù)是否登錄");
Object userId = checkUser(session);
if (userId != null) {
logger.info("獲取用戶(hù)信息");
User user = userService.get(Integer.parseInt(userId.toString()));
map.put("user", user);
logger.info("獲取用戶(hù)所在地區(qū)級(jí)地址");
String districtAddressId = user.getUser_address().getAddress_areaId();
Address districtAddress = addressService.get(districtAddressId);
logger.info("獲取市級(jí)地址信息");
Address cityAddress = addressService.get(districtAddress.getAddress_regionId().getAddress_areaId());
logger.info("獲取其他地址信息");
List<Address> addressList = addressService.getRoot();
List<Address> cityList = addressService.getList(null,cityAddress.getAddress_regionId().getAddress_areaId());
List<Address> districtList = addressService.getList(null,cityAddress.getAddress_areaId());
map.put("addressList", addressList);
map.put("cityList", cityList);
map.put("districtList", districtList);
map.put("addressId", cityAddress.getAddress_regionId().getAddress_areaId());
map.put("cityAddressId", cityAddress.getAddress_areaId());
map.put("districtAddressId", districtAddressId);
return "fore/userDetails";
} else {
return "redirect:/login";
}
}
//前臺(tái)天貓-用戶(hù)更換頭像
@ResponseBody
@RequestMapping(value = "user/uploadUserHeadImage", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
public String uploadUserHeadImage(@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/userProfilePicture/" + fileName;
logger.info("文件上傳路徑:{}", filePath);
JSONObject jsonObject = new JSONObject();
try {
logger.info("文件上傳中...");
file.transferTo(new File(filePath));
logger.info("文件上傳成功!");
jsonObject.put("success", true);
jsonObject.put("fileName", fileName);
} catch (IOException e) {
logger.warn("文件上傳失??!");
e.printStackTrace();
jsonObject.put("success", false);
}
return jsonObject.toJSONString();
}
//前臺(tái)天貓-用戶(hù)詳情更新
@RequestMapping(value="user/update",method=RequestMethod.POST,produces ="application/json;charset=utf-8")
public String userUpdate(HttpSession session, Map<String,Object> map,
@RequestParam(value = "user_nickname") String user_nickname /*用戶(hù)昵稱(chēng) */,
@RequestParam(value = "user_realname") String user_realname /*真實(shí)姓名*/,
@RequestParam(value = "user_gender") String user_gender /*用戶(hù)性別*/,
@RequestParam(value = "user_birthday") String user_birthday /*用戶(hù)生日*/,
@RequestParam(value = "user_address") String user_address /*用戶(hù)所在地 */,
@RequestParam(value = "user_profile_picture_src", required = false) String user_profile_picture_src /* 用戶(hù)頭像*/,
@RequestParam(value = "user_password") String user_password/* 用戶(hù)密碼 */
) throws ParseException, UnsupportedEncodingException {
logger.info("檢查用戶(hù)是否登錄");
Object userId = checkUser(session);
if (userId != null) {
logger.info("獲取用戶(hù)信息");
User user = userService.get(Integer.parseInt(userId.toString()));
map.put("user", user);
} else {
return "redirect:/login";
}
logger.info("創(chuàng)建用戶(hù)對(duì)象");
if (user_profile_picture_src != null && "".equals(user_profile_picture_src)) {
user_profile_picture_src = null;
}
User userUpdate = new User()
.setUser_id(Integer.parseInt(userId.toString()))
.setUser_nickname(new String(user_nickname.getBytes("ISO8859-1"),"UTF-8"))
.setUser_realname(new String(user_realname.getBytes("ISO8859-1"),"UTF-8"))
.setUser_gender(Byte.valueOf(user_gender))
.setUser_birthday(new SimpleDateFormat("yyyy-MM-dd").parse(user_birthday))
.setUser_address(new Address().setAddress_areaId(user_address))
.setUser_profile_picture_src(user_profile_picture_src)
.setUser_password(user_password);
logger.info("執(zhí)行修改");
if (userService.update(userUpdate)){
logger.info("修改成功!跳轉(zhuǎn)到用戶(hù)詳情頁(yè)面");
return "redirect:/userDetails";
}
throw new RuntimeException();
}
}用戶(hù)訂單控制層
@Controller
public class ForeOrderController extends BaseController {
@Autowired
private ProductService productService;
@Autowired
private UserService userService;
@Autowired
private ProductOrderItemService productOrderItemService;
@Autowired
private AddressService addressService;
@Autowired
private CategoryService categoryService;
@Autowired
private ProductImageService productImageService;
@Autowired
private ProductOrderService productOrderService;
@Autowired
private ReviewService reviewService;
@Autowired
private LastIDService lastIDService;
//轉(zhuǎn)到前臺(tái)天貓-訂單列表頁(yè)
@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/* 頁(yè)數(shù) */,
@PathVariable("count") Integer count/* 行數(shù)*/) {
logger.info("檢查用戶(hù)是否登錄");
Object userId = checkUser(session);
User user;
if (userId != null) {
logger.info("獲取用戶(hù)信息");
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("根據(jù)用戶(hù)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);
//訂單總數(shù)量
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("獲取訂單項(xiàng)信息及對(duì)應(yīng)的產(chǎn)品信息");
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("獲取產(chǎn)品分類(lèi)列表信息");
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("轉(zhuǎn)到前臺(tái)天貓-訂單列表頁(yè)");
return "fore/orderListPage";
}
//轉(zhuǎn)到前臺(tái)天貓-訂單建立頁(yè)
@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("檢查用戶(hù)是否登錄");
Object userId = checkUser(session);
User user;
if (userId != null) {
logger.info("獲取用戶(hù)信息");
user = userService.get(Integer.parseInt(userId.toString()));
map.put("user", user);
} else {
return "redirect:/login";
}
logger.info("通過(guò)產(chǎn)品ID獲取產(chǎn)品信息:{}", product_id);
Product product = productService.get(product_id);
if (product == null) {
return "redirect:/";
}
logger.info("獲取產(chǎn)品的詳細(xì)信息");
product.setProduct_category(categoryService.get(product.getProduct_category().getCategory_id()));
product.setSingleProductImageList(productImageService.getList(product_id, (byte) 0, new PageUtil(0, 1)));
logger.info("封裝訂單項(xiàng)對(duì)象");
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();
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為{}的市級(jí)地址信息", addressId);
List<Address> cityAddress = addressService.getList(null, addressId);
logger.info("獲取cityAddressId為{}的區(qū)級(jí)地址信息", 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("轉(zhuǎn)到前臺(tái)天貓-訂單建立頁(yè)");
return "fore/productBuyPage";
}
//轉(zhuǎn)到前臺(tái)天貓-購(gòu)物車(chē)訂單建立頁(yè)
@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("檢查用戶(hù)是否登錄");
Object userId = checkUser(session);
User user;
if (userId != null) {
logger.info("獲取用戶(hù)信息");
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("用戶(hù)訂單項(xiàng)數(shù)組不存在,回到購(gòu)物車(chē)頁(yè)");
return "redirect:/cart";
}
logger.info("通過(guò)訂單項(xiàng)ID數(shù)組獲取訂單信息");
List<ProductOrderItem> orderItemList = new ArrayList<>(order_item_list.length);
for (Integer orderItem_id : order_item_list) {
orderItemList.add(productOrderItemService.get(orderItem_id));
}
logger.info("------檢查訂單項(xiàng)合法性------");
if (orderItemList.size() == 0) {
logger.warn("用戶(hù)訂單項(xiàng)獲取失敗,回到購(gòu)物車(chē)頁(yè)");
return "redirect:/cart";
}
for (ProductOrderItem orderItem : orderItemList) {
if (orderItem.getProductOrderItem_user().getUser_id() != userId) {
logger.warn("用戶(hù)訂單項(xiàng)與用戶(hù)不匹配,回到購(gòu)物車(chē)頁(yè)");
return "redirect:/cart";
}
if (orderItem.getProductOrderItem_order() != null) {
logger.warn("用戶(hù)訂單項(xiàng)不屬于購(gòu)物車(chē),回到購(gòu)物車(chē)頁(yè)");
return "redirect:/cart";
}
}
logger.info("驗(yàn)證通過(guò),獲取訂單項(xiàng)的產(chǎn)品信息");
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為{}的市級(jí)地址信息", addressId);
List<Address> cityAddress = addressService.getList(null, addressId);
logger.info("獲取cityAddressId為{}的區(qū)級(jí)地址信息", 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("轉(zhuǎn)到前臺(tái)天貓-訂單建立頁(yè)");
return "fore/productBuyPage";
}
//轉(zhuǎn)到前臺(tái)天貓-訂單支付頁(yè)
@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("檢查用戶(hù)是否登錄");
Object userId = checkUser(session);
User user;
if (userId != null) {
logger.info("獲取用戶(hù)信息");
user = userService.get(Integer.parseInt(userId.toString()));
map.put("user", user);
} else {
return "redirect:/login";
}
logger.info("------驗(yàn)證訂單信息------");
logger.info("查詢(xún)訂單是否存在");
ProductOrder order = productOrderService.getByCode(order_code);
if (order == null) {
logger.warn("訂單不存在,返回訂單列表頁(yè)");
return "redirect:/order/0/10";
}
logger.info("驗(yàn)證訂單狀態(tài)");
if (order.getProductOrder_status() != 0) {
logger.warn("訂單狀態(tài)不正確,返回訂單列表頁(yè)");
return "redirect:/order/0/10";
}
logger.info("驗(yàn)證用戶(hù)與訂單是否一致");
if (order.getProductOrder_user().getUser_id() != Integer.parseInt(userId.toString())) {
logger.warn("用戶(hù)與訂單信息不一致,返回訂單列表頁(yè)");
return "redirect:/order/0/10";
}
order.setProductOrderItemList(productOrderItemService.getListByOrderId(order.getProductOrder_id(), null));
double orderTotalPrice = 0.00;
if (order.getProductOrderItemList().size() == 1) {
logger.info("獲取單訂單項(xiàng)的產(chǎn)品信息");
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("轉(zhuǎn)到前臺(tái)天貓-訂單支付頁(yè)");
return "fore/productPayPage";
}
//轉(zhuǎn)到前臺(tái)天貓-訂單支付成功頁(yè)
@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("檢查用戶(hù)是否登錄");
Object userId = checkUser(session);
User user;
if (userId != null) {
logger.info("獲取用戶(hù)信息");
user = userService.get(Integer.parseInt(userId.toString()));
map.put("user", user);
} else {
return "redirect:/login";
}
logger.info("------驗(yàn)證訂單信息------");
logger.info("查詢(xún)訂單是否存在");
ProductOrder order = productOrderService.getByCode(order_code);
if (order == null) {
logger.warn("訂單不存在,返回訂單列表頁(yè)");
return "redirect:/order/0/10";
}
logger.info("驗(yàn)證訂單狀態(tài)");
if (order.getProductOrder_status() != 1) {
logger.warn("訂單狀態(tài)不正確,返回訂單列表頁(yè)");
return "redirect:/order/0/10";
}
logger.info("驗(yàn)證用戶(hù)與訂單是否一致");
if (order.getProductOrder_user().getUser_id() != Integer.parseInt(userId.toString())) {
logger.warn("用戶(hù)與訂單信息不一致,返回訂單列表頁(yè)");
return "redirect:/order/0/10";
}
order.setProductOrderItemList(productOrderItemService.getListByOrderId(order.getProductOrder_id(), null));
double orderTotalPrice = 0.00;
if (order.getProductOrderItemList().size() == 1) {
logger.info("獲取單訂單項(xiàng)的產(chǎn)品信息");
ProductOrderItem productOrderItem = order.getProductOrderItemList().get(0);
orderTotalPrice = productOrderItem.getProductOrderItem_price();
} else {
for (ProductOrderItem productOrderItem : order.getProductOrderItemList()) {
orderTotalPrice += productOrderItem.getProductOrderItem_price();
}
}
logger.info("訂單總金額為:{}元", orderTotalPrice);
logger.info("獲取訂單詳情-地址信息");
Address address = addressService.get(order.getProductOrder_address().getAddress_areaId());
Stack<String> addressStack = new Stack<>();
//詳細(xì)地址
addressStack.push(order.getProductOrder_detail_address());
//最后一級(jí)地址
addressStack.push(address.getAddress_name() + " ");
//如果不是第一級(jí)地址
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("轉(zhuǎn)到前臺(tái)天貓-訂單支付成功頁(yè)");
return "fore/productPaySuccessPage";
}
//轉(zhuǎn)到前臺(tái)天貓-訂單確認(rèn)頁(yè)
@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("檢查用戶(hù)是否登錄");
Object userId = checkUser(session);
User user;
if (userId != null) {
logger.info("獲取用戶(hù)信息");
user = userService.get(Integer.parseInt(userId.toString()));
map.put("user", user);
} else {
return "redirect:/login";
}
logger.info("------驗(yàn)證訂單信息------");
logger.info("查詢(xún)訂單是否存在");
ProductOrder order = productOrderService.getByCode(order_code);
if (order == null) {
logger.warn("訂單不存在,返回訂單列表頁(yè)");
return "redirect:/order/0/10";
}
logger.info("驗(yàn)證訂單狀態(tài)");
if (order.getProductOrder_status() != 2) {
logger.warn("訂單狀態(tài)不正確,返回訂單列表頁(yè)");
return "redirect:/order/0/10";
}
logger.info("驗(yàn)證用戶(hù)與訂單是否一致");
if (order.getProductOrder_user().getUser_id() != Integer.parseInt(userId.toString())) {
logger.warn("用戶(hù)與訂單信息不一致,返回訂單列表頁(yè)");
return "redirect:/order/0/10";
}
order.setProductOrderItemList(productOrderItemService.getListByOrderId(order.getProductOrder_id(), null));
double orderTotalPrice = 0.00;
if (order.getProductOrderItemList().size() == 1) {
logger.info("獲取單訂單項(xiàng)的產(chǎn)品信息");
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("獲取多訂單項(xiàng)的產(chǎn)品信息");
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("轉(zhuǎn)到前臺(tái)天貓-訂單確認(rèn)頁(yè)");
return "fore/orderConfirmPage";
}
//轉(zhuǎn)到前臺(tái)天貓-訂單完成頁(yè)
@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("檢查用戶(hù)是否登錄");
Object userId = checkUser(session);
User user;
if (userId != null) {
logger.info("獲取用戶(hù)信息");
user = userService.get(Integer.parseInt(userId.toString()));
map.put("user", user);
} else {
return "redirect:/login";
}
logger.info("------驗(yàn)證訂單信息------");
logger.info("查詢(xún)訂單是否存在");
ProductOrder order = productOrderService.getByCode(order_code);
if (order == null) {
logger.warn("訂單不存在,返回訂單列表頁(yè)");
return "redirect:/order/0/10";
}
logger.info("驗(yàn)證訂單狀態(tài)");
if (order.getProductOrder_status() != 3) {
logger.warn("訂單狀態(tài)不正確,返回訂單列表頁(yè)");
return "redirect:/order/0/10";
}
logger.info("驗(yàn)證用戶(hù)與訂單是否一致");
if (order.getProductOrder_user().getUser_id() != Integer.parseInt(userId.toString())) {
logger.warn("用戶(hù)與訂單信息不一致,返回訂單列表頁(yè)");
return "redirect:/order/0/10";
}
logger.info("獲取訂單中訂單項(xiàng)數(shù)量");
Integer count = productOrderItemService.getTotalByOrderId(order.getProductOrder_id());
Product product = null;
if (count == 1) {
logger.info("獲取訂單中的唯一訂單項(xiàng)");
ProductOrderItem productOrderItem = productOrderItemService.getListByOrderId(order.getProductOrder_id(), new PageUtil(0, 1)).get(0);
if (productOrderItem != null) {
logger.info("獲取訂單項(xiàng)評(píng)論數(shù)量");
count = reviewService.getTotalByOrderItemId(productOrderItem.getProductOrderItem_id());
if (count == 0) {
logger.info("獲取訂單項(xiàng)產(chǎn)品信息");
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("轉(zhuǎn)到前臺(tái)天貓-訂單完成頁(yè)");
return "fore/orderSuccessPage";
}
//轉(zhuǎn)到前臺(tái)天貓-購(gòu)物車(chē)頁(yè)
@RequestMapping(value = "cart", method = RequestMethod.GET)
public String goToCartPage(Map<String, Object> map, HttpSession session) {
logger.info("檢查用戶(hù)是否登錄");
Object userId = checkUser(session);
User user;
if (userId != null) {
logger.info("獲取用戶(hù)信息");
user = userService.get(Integer.parseInt(userId.toString()));
map.put("user", user);
} else {
return "redirect:/login";
}
logger.info("獲取用戶(hù)購(gòu)物車(chē)信息");
List<ProductOrderItem> orderItemList = productOrderItemService.getListByUserId(Integer.valueOf(userId.toString()), null);
Integer orderItemTotal = 0;
if (orderItemList.size() > 0) {
logger.info("獲取用戶(hù)購(gòu)物車(chē)的商品總數(shù)");
orderItemTotal = productOrderItemService.getTotalByUserId(Integer.valueOf(userId.toString()));
logger.info("獲取用戶(hù)購(gòu)物車(chē)內(nèi)的商品信息");
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("轉(zhuǎn)到前臺(tái)天貓-購(gòu)物車(chē)頁(yè)");
return "fore/productBuyCarPage";
}
//更新訂單信息為已支付,待發(fā)貨-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("檢查用戶(hù)是否登錄");
Object userId = checkUser(session);
if (userId == null) {
object.put("success", false);
object.put("url", "/login");
return object.toJSONString();
}
logger.info("------驗(yàn)證訂單信息------");
logger.info("查詢(xún)訂單是否存在");
ProductOrder order = productOrderService.getByCode(order_code);
if (order == null) {
logger.warn("訂單不存在,返回訂單列表頁(yè)");
object.put("success", false);
object.put("url", "/order/0/10");
return object.toJSONString();
}
logger.info("驗(yàn)證訂單狀態(tài)");
if (order.getProductOrder_status() != 0) {
logger.warn("訂單狀態(tài)不正確,返回訂單列表頁(yè)");
object.put("success", false);
object.put("url", "/order/0/10");
return object.toJSONString();
}
logger.info("驗(yàn)證用戶(hù)與訂單是否一致");
if (order.getProductOrder_user().getUser_id() != Integer.parseInt(userId.toString())) {
logger.warn("用戶(hù)與訂單信息不一致,返回訂單列表頁(yè)");
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("獲取單訂單項(xiàng)的產(chǎn)品信息");
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);
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();
}
//更新訂單信息為已發(fā)貨,待確認(rèn)-ajax
@RequestMapping(value = "order/delivery/{order_code}", method = RequestMethod.GET)
public String orderDelivery(HttpSession session, @PathVariable("order_code") String order_code) {
logger.info("檢查用戶(hù)是否登錄");
Object userId = checkUser(session);
if (userId == null) {
return "redirect:/order/0/10";
}
logger.info("------驗(yàn)證訂單信息------");
logger.info("查詢(xún)訂單是否存在");
ProductOrder order = productOrderService.getByCode(order_code);
if (order == null) {
logger.warn("訂單不存在,返回訂單列表頁(yè)");
return "redirect:/order/0/10";
}
logger.info("驗(yàn)證訂單狀態(tài)");
if (order.getProductOrder_status() != 1) {
logger.warn("訂單狀態(tài)不正確,返回訂單列表頁(yè)");
return "redirect:/order/0/10";
}
logger.info("驗(yàn)證用戶(hù)與訂單是否一致");
if (order.getProductOrder_user().getUser_id() != Integer.parseInt(userId.toString())) {
logger.warn("用戶(hù)與訂單信息不一致,返回訂單列表頁(yè)");
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("檢查用戶(hù)是否登錄");
Object userId = checkUser(session);
if (userId == null) {
object.put("success", false);
object.put("url", "/login");
return object.toJSONString();
}
logger.info("------驗(yàn)證訂單信息------");
logger.info("查詢(xún)訂單是否存在");
ProductOrder order = productOrderService.getByCode(order_code);
if (order == null) {
logger.warn("訂單不存在,返回訂單列表頁(yè)");
object.put("success", false);
object.put("url", "/order/0/10");
return object.toJSONString();
}
logger.info("驗(yàn)證訂單狀態(tài)");
if (order.getProductOrder_status() != 2) {
logger.warn("訂單狀態(tài)不正確,返回訂單列表頁(yè)");
object.put("success", false);
object.put("url", "/order/0/10");
return object.toJSONString();
}
logger.info("驗(yàn)證用戶(hù)與訂單是否一致");
if (order.getProductOrder_user().getUser_id() != Integer.parseInt(userId.toString())) {
logger.warn("用戶(hù)與訂單信息不一致,返回訂單列表頁(yè)");
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();
}
//更新訂單信息為交易關(guān)閉-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("檢查用戶(hù)是否登錄");
Object userId = checkUser(session);
if (userId == null) {
object.put("success", false);
object.put("url", "/login");
return object.toJSONString();
}
logger.info("------驗(yàn)證訂單信息------");
logger.info("查詢(xún)訂單是否存在");
ProductOrder order = productOrderService.getByCode(order_code);
if (order == null) {
logger.warn("訂單不存在,返回訂單列表頁(yè)");
object.put("success", false);
object.put("url", "/order/0/10");
return object.toJSONString();
}
logger.info("驗(yàn)證訂單狀態(tài)");
if (order.getProductOrder_status() != 0) {
logger.warn("訂單狀態(tài)不正確,返回訂單列表頁(yè)");
object.put("success", false);
object.put("url", "/order/0/10");
return object.toJSONString();
}
logger.info("驗(yàn)證用戶(hù)與訂單是否一致");
if (order.getProductOrder_user().getUser_id() != Integer.parseInt(userId.toString())) {
logger.warn("用戶(hù)與訂單信息不一致,返回訂單列表頁(yè)");
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();
}
//更新購(gòu)物車(chē)訂單項(xiàng)數(shù)量-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("檢查用戶(hù)是否登錄");
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("更新產(chǎn)品訂單項(xiàng)數(shù)量");
for (String key : orderItemIDSet) {
ProductOrderItem productOrderItem = productOrderItemService.get(Integer.valueOf(key));
if (productOrderItem == null || !productOrderItem.getProductOrderItem_user().getUser_id().equals(userId)) {
logger.warn("訂單項(xiàng)為空或用戶(hù)狀態(tài)不一致!");
object.put("success", false);
return object.toJSONString();
}
if (productOrderItem.getProductOrderItem_order() != null) {
logger.warn("用戶(hù)訂單項(xiàng)不屬于購(gòu)物車(chē),回到購(gòu)物車(chē)頁(yè)");
return "redirect:/cart";
}
Short number = Short.valueOf(orderItemString.getString(key));
if (number <= 0 || number > 500) {
logger.warn("訂單項(xiàng)產(chǎn)品數(shù)量不合法!");
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("無(wú)訂單項(xiàng)可以處理");
object.put("success", false);
return object.toJSONString();
}
}
//創(chuàng)建新訂單-單訂單項(xiàng)-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("檢查用戶(hù)是否登錄");
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();
}
logger.info("將收貨地址等相關(guān)信息存入Cookie中");
Cookie cookie1 = new Cookie("addressId", addressId);
Cookie cookie2 = new Cookie("cityAddressId", cityAddressId);
Cookie cookie3 = new Cookie("districtAddressId", districtAddressId);
Cookie cookie4 = new Cookie("order_post", URLEncoder.encode(productOrder_post, "UTF-8"));
Cookie cookie5 = new Cookie("order_receiver", URLEncoder.encode(productOrder_receiver, "UTF-8"));
Cookie cookie6 = new Cookie("order_phone", URLEncoder.encode(productOrder_mobile, "UTF-8"));
Cookie cookie7 = new Cookie("detailsAddress", URLEncoder.encode(productOrder_detail_address, "UTF-8"));
//設(shè)置過(guò)期時(shí)間為一年
int maxAge = 60 * 60 * 24 * 365;
cookie1.setMaxAge(maxAge);
cookie2.setMaxAge(maxAge);
cookie3.setMaxAge(maxAge);
cookie4.setMaxAge(maxAge);
cookie5.setMaxAge(maxAge);
cookie6.setMaxAge(maxAge);
cookie7.setMaxAge(maxAge);
response.addCookie(cookie1);
response.addCookie(cookie2);
response.addCookie(cookie3);
response.addCookie(cookie4);
response.addCookie(cookie5);
response.addCookie(cookie6);
response.addCookie(cookie7);
StringBuffer productOrder_code = new StringBuffer()
.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()))
.append(0)
.append(userId);
logger.info("生成的訂單號(hào)為:{}", productOrder_code);
logger.info("整合訂單對(duì)象");
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("整合訂單項(xiàng)對(duì)象");
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();
}
//創(chuàng)建新訂單-多訂單項(xiàng)-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("檢查用戶(hù)是否登錄");
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("訂單項(xiàng)為空或用戶(hù)狀態(tài)不一致!");
object.put("success", false);
object.put("url", "/cart");
return object.toJSONString();
}
if (orderItem.getProductOrderItem_order() != null) {
logger.warn("用戶(hù)訂單項(xiàng)不屬于購(gòu)物車(chē),回到購(gòu)物車(chē)頁(yè)");
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("將收貨地址等相關(guān)信息存入Cookie中");
Cookie cookie1 = new Cookie("addressId", addressId);
Cookie cookie2 = new Cookie("cityAddressId", cityAddressId);
Cookie cookie3 = new Cookie("districtAddressId", districtAddressId);
Cookie cookie4 = new Cookie("order_post", URLEncoder.encode(productOrder_post, "UTF-8"));
Cookie cookie5 = new Cookie("order_receiver", URLEncoder.encode(productOrder_receiver, "UTF-8"));
Cookie cookie6 = new Cookie("order_phone", URLEncoder.encode(productOrder_mobile, "UTF-8"));
Cookie cookie7 = new Cookie("detailsAddress", URLEncoder.encode(productOrder_detail_address, "UTF-8"));
//設(shè)置過(guò)期時(shí)間為一年
int maxAge = 60 * 60 * 24 * 365;
cookie1.setMaxAge(maxAge);
cookie2.setMaxAge(maxAge);
cookie3.setMaxAge(maxAge);
cookie4.setMaxAge(maxAge);
cookie5.setMaxAge(maxAge);
cookie6.setMaxAge(maxAge);
cookie7.setMaxAge(maxAge);
response.addCookie(cookie1);
response.addCookie(cookie2);
response.addCookie(cookie3);
response.addCookie(cookie4);
response.addCookie(cookie5);
response.addCookie(cookie6);
response.addCookie(cookie7);
StringBuffer productOrder_code = new StringBuffer()
.append(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()))
.append(0)
.append(userId);
logger.info("生成的訂單號(hào)為:{}", productOrder_code);
logger.info("整合訂單對(duì)象");
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("整合訂單項(xiàng)對(duì)象");
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();
}
//創(chuàng)建訂單項(xiàng)-購(gòu)物車(chē)-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("檢查用戶(hù)是否登錄");
Object userId = checkUser(session);
if (userId == null) {
object.put("url", "/login");
object.put("success", false);
return object.toJSONString();
}
logger.info("通過(guò)產(chǎn)品ID獲取產(chǎn)品信息:{}", 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("檢查用戶(hù)的購(gòu)物車(chē)項(xiàng)");
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("找到已有的產(chǎn)品,進(jìn)行數(shù)量追加");
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("封裝訂單項(xiàng)對(duì)象");
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();
}
//刪除訂單項(xiàng)-購(gòu)物車(chē)-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("檢查用戶(hù)是否登錄");
Object userId = checkUser(session);
if (userId == null) {
object.put("url", "/login");
object.put("success", false);
return object.toJSONString();
}
logger.info("檢查用戶(hù)的購(gòu)物車(chē)項(xiàng)");
List<ProductOrderItem> orderItemList = productOrderItemService.getListByUserId(Integer.valueOf(userId.toString()), null);
boolean isMine = false;
for (ProductOrderItem orderItem : orderItemList) {
logger.info("找到匹配的購(gòu)物車(chē)項(xiàng)");
if (orderItem.getProductOrderItem_id().equals(orderItem_id)) {
isMine = true;
break;
}
}
if (isMine) {
logger.info("刪除訂單項(xiàng)信息");
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();
}
}后臺(tái)管理員品類(lèi)控制層
/**
* 后臺(tái)管理-分類(lèi)頁(yè)
*/
@Controller
public class CategoryController extends BaseController {
@Autowired
private CategoryService categoryService;
@Autowired
private LastIDService lastIDService;
@Autowired
private PropertyService propertyService;
//轉(zhuǎn)到后臺(tái)管理-分類(lèi)頁(yè)-ajax
@RequestMapping(value = "admin/category", method = RequestMethod.GET)
public String goToPage(HttpSession session, Map<String, Object> map) {
logger.info("檢查管理員權(quán)限");
Object adminId = checkAdmin(session);
if (adminId == null) {
return "admin/include/loginMessage";
}
logger.info("獲取前10條分類(lèi)列表");
PageUtil pageUtil = new PageUtil(0, 10);
List<Category> categoryList = categoryService.getList(null, pageUtil);
map.put("categoryList", categoryList);
logger.info("獲取分類(lèi)總數(shù)量");
Integer categoryCount = categoryService.getTotal(null);
map.put("categoryCount", categoryCount);
logger.info("獲取分頁(yè)信息");
pageUtil.setTotal(categoryCount);
map.put("pageUtil", pageUtil);
logger.info("轉(zhuǎn)到后臺(tái)管理-分類(lèi)頁(yè)-ajax方式");
return "admin/categoryManagePage";
}
//轉(zhuǎn)到后臺(tái)管理-分類(lèi)詳情頁(yè)-ajax
@RequestMapping(value = "admin/category/{cid}", method = RequestMethod.GET)
public String goToDetailsPage(HttpSession session, Map<String, Object> map, @PathVariable Integer cid/* 分類(lèi)ID */) {
logger.info("檢查管理員權(quán)限");
Object adminId = checkAdmin(session);
if (adminId == null) {
return "admin/include/loginMessage";
}
logger.info("獲取category_id為{}的分類(lèi)信息", cid);
Category category = categoryService.get(cid);
logger.info("獲取分類(lèi)子信息-屬性列表");
category.setPropertyList(propertyService.getList(new Property().setProperty_category(category), null));
map.put("category", category);
logger.info("轉(zhuǎn)到后臺(tái)管理-分類(lèi)詳情頁(yè)-ajax方式");
return "admin/include/categoryDetails";
}
//轉(zhuǎn)到后臺(tái)管理-分類(lèi)添加頁(yè)-ajax
@RequestMapping(value = "admin/category/new", method = RequestMethod.GET)
public String goToAddPage(HttpSession session, Map<String, Object> map) {
logger.info("檢查管理員權(quán)限");
Object adminId = checkAdmin(session);
if (adminId == null) {
return "admin/include/loginMessage";
}
logger.info("轉(zhuǎn)到后臺(tái)管理-分類(lèi)添加頁(yè)-ajax方式");
return "admin/include/categoryDetails";
}
//添加分類(lèi)信息-ajax
@ResponseBody
@RequestMapping(value = "admin/category", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
public String addCategory(@RequestParam String category_name/* 分類(lèi)名稱(chēng) */,
@RequestParam String category_image_src/* 分類(lèi)圖片路徑 */) {
JSONObject jsonObject = new JSONObject();
logger.info("整合分類(lèi)信息");
Category category = new Category()
.setCategory_name(category_name)
.setCategory_image_src(category_image_src.substring(category_image_src.lastIndexOf("/") + 1));
logger.info("添加分類(lèi)信息");
boolean yn = categoryService.add(category);
if (yn) {
int category_id = lastIDService.selectLastID();
logger.info("添加成功!,新增分類(lèi)的ID值為:{}", category_id);
jsonObject.put("success", true);
jsonObject.put("category_id", category_id);
} else {
jsonObject.put("success", false);
logger.warn("添加失敗!事務(wù)回滾");
throw new RuntimeException();
}
return jsonObject.toJSONString();
}
//更新分類(lèi)信息-ajax
@ResponseBody
@RequestMapping(value = "admin/category/{category_id}", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
public String updateCategory(@RequestParam String category_name/* 分類(lèi)名稱(chēng) */,
@RequestParam String category_image_src/* 分類(lèi)圖片路徑 */,
@PathVariable("category_id") Integer category_id/* 分類(lèi)ID */) {
JSONObject jsonObject = new JSONObject();
logger.info("整合分類(lèi)信息");
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("更新分類(lèi)信息,分類(lèi)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("更新失?。∈聞?wù)回滾");
throw new RuntimeException();
}
return jsonObject.toJSONString();
}
//按條件查詢(xún)分類(lèi)-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/* 分類(lèi)名稱(chēng) */,
@PathVariable Integer index/* 頁(yè)數(shù) */,
@PathVariable Integer count/* 行數(shù) */) 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("按條件獲取第{}頁(yè)的{}條分類(lèi)", 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("按條件獲取分類(lèi)總數(shù)量");
Integer categoryCount = categoryService.getTotal(category_name);
object.put("categoryCount", categoryCount);
logger.info("獲取分頁(yè)信息");
pageUtil.setTotal(categoryCount);
object.put("totalPage", pageUtil.getTotalPage());
object.put("pageUtil", pageUtil);
return object.toJSONString();
}
// 上傳分類(lèi)圖片-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();
}
}后臺(tái)管理-產(chǎn)品頁(yè)控制層
/**
* 后臺(tái)管理-產(chǎn)品頁(yè)
*/
@Controller
public class ProductController extends BaseController{
@Autowired
private CategoryService categoryService;
@Autowired
private ProductService productService;
@Autowired
private ProductImageService productImageService;
@Autowired
private PropertyService propertyService;
@Autowired
private PropertyValueService propertyValueService;
@Autowired
private LastIDService lastIDService;
//轉(zhuǎn)到后臺(tái)管理-產(chǎn)品頁(yè)-ajax
@RequestMapping(value = "admin/product",method = RequestMethod.GET)
public String goToPage(HttpSession session, Map<String, Object> map) {
logger.info("檢查管理員權(quán)限");
Object adminId = checkAdmin(session);
if(adminId == null){
return "admin/include/loginMessage";
}
logger.info("獲取產(chǎn)品分類(lèi)列表");
List<Category> categoryList = categoryService.getList(null, null);
map.put("categoryList", categoryList);
logger.info("獲取前10條產(chǎn)品列表");
PageUtil pageUtil = new PageUtil(0, 10);
List<Product> productList = productService.getList(null, null, null, pageUtil);
map.put("productList", productList);
logger.info("獲取產(chǎn)品總數(shù)量");
Integer productCount = productService.getTotal(null, null);
map.put("productCount", productCount);
logger.info("獲取分頁(yè)信息");
pageUtil.setTotal(productCount);
map.put("pageUtil", pageUtil);
logger.info("轉(zhuǎn)到后臺(tái)管理-產(chǎn)品頁(yè)-ajax方式");
return "admin/productManagePage";
}
//轉(zhuǎn)到后臺(tái)管理-產(chǎn)品詳情頁(yè)-ajax
@RequestMapping(value="admin/product/{pid}",method = RequestMethod.GET)
public String goToDetailsPage(HttpSession session, Map<String, Object> map, @PathVariable Integer pid/* 產(chǎn)品ID */) {
logger.info("檢查管理員權(quán)限");
Object adminId = checkAdmin(session);
if(adminId == null){
return "admin/include/loginMessage";
}
logger.info("獲取product_id為{}的產(chǎn)品信息",pid);
Product product = productService.get(pid);
logger.info("獲取產(chǎn)品詳情-圖片信息");
Integer product_id =product.getProduct_id();
List<ProductImage> productImageList = productImageService.getList(product_id, null, null);
List<ProductImage> singleProductImageList = new ArrayList<>(5);
List<ProductImage> detailsProductImageList = new ArrayList<>(8);
for (ProductImage productImage : productImageList) {
if (productImage.getProductImage_type() == 0) {
singleProductImageList.add(productImage);
} else {
detailsProductImageList.add(productImage);
}
}
product.setSingleProductImageList(singleProductImageList);
product.setDetailProductImageList(detailsProductImageList);
map.put("product",product);
logger.info("獲取產(chǎn)品詳情-屬性值信息");
List<PropertyValue> propertyValueList = propertyValueService.getList(new PropertyValue().setPropertyValue_product(product),null);
logger.info("獲取產(chǎn)品詳情-分類(lèi)信息對(duì)應(yīng)的屬性列表");
List<Property> propertyList = propertyService.getList(new Property().setProperty_category(product.getProduct_category()),null);
logger.info("屬性列表和屬性值列表合并");
for(Property property : propertyList){
for(PropertyValue propertyValue : propertyValueList){
if(property.getProperty_id().equals(propertyValue.getPropertyValue_property().getProperty_id())){
List<PropertyValue> property_value_item = new ArrayList<>(1);
property_value_item.add(propertyValue);
property.setPropertyValueList(property_value_item);
break;
}
}
}
map.put("propertyList",propertyList);
logger.info("獲取分類(lèi)列表");
List<Category> categoryList = categoryService.getList(null,null);
map.put("categoryList",categoryList);
logger.info("轉(zhuǎn)到后臺(tái)管理-產(chǎn)品詳情頁(yè)-ajax方式");
return "admin/include/productDetails";
}
//轉(zhuǎn)到后臺(tái)管理-產(chǎn)品添加頁(yè)-ajax
@RequestMapping(value = "admin/product/new",method = RequestMethod.GET)
public String goToAddPage(HttpSession session,Map<String, Object> map){
logger.info("檢查管理員權(quán)限");
Object adminId = checkAdmin(session);
if(adminId == null){
return "admin/include/loginMessage";
}
logger.info("獲取分類(lèi)列表");
List<Category> categoryList = categoryService.getList(null,null);
map.put("categoryList",categoryList);
logger.info("獲取第一個(gè)分類(lèi)信息對(duì)應(yīng)的屬性列表");
List<Property> propertyList = propertyService.getList(new Property().setProperty_category(categoryList.get(0)),null);
map.put("propertyList",propertyList);
logger.info("轉(zhuǎn)到后臺(tái)管理-產(chǎn)品添加頁(yè)-ajax方式");
return "admin/include/productDetails";
}
//添加產(chǎn)品信息-ajax.
@ResponseBody
@RequestMapping(value = "admin/product", method = RequestMethod.POST,produces = "application/json;charset=utf-8")
public String addProduct(@RequestParam String product_name/* 產(chǎn)品名稱(chēng) */,
@RequestParam String product_title/* 產(chǎn)品標(biāo)題 */,
@RequestParam Integer product_category_id/* 產(chǎn)品類(lèi)型ID */,
@RequestParam Double product_sale_price/* 產(chǎn)品最低價(jià) */,
@RequestParam Double product_price/* 產(chǎn)品最高價(jià) */,
@RequestParam Byte product_isEnabled/* 產(chǎn)品狀態(tài) */,
@RequestParam String propertyJson/* 產(chǎn)品屬性JSON */,
@RequestParam(required = false) String[] productSingleImageList/*產(chǎn)品預(yù)覽圖片名稱(chēng)數(shù)組*/,
@RequestParam(required = false) String[] productDetailsImageList/*產(chǎn)品詳情圖片名稱(chēng)數(shù)組*/) {
JSONObject jsonObject = new JSONObject();
logger.info("整合產(chǎn)品信息");
Product product = new Product()
.setProduct_name(product_name)
.setProduct_title(product_title)
.setProduct_category(new Category().setCategory_id(product_category_id))
.setProduct_sale_price(product_sale_price)
.setProduct_price(product_price)
.setProduct_isEnabled(product_isEnabled)
.setProduct_create_date(new Date());
logger.info("添加產(chǎn)品信息");
boolean yn = productService.add(product);
if (!yn) {
logger.warn("產(chǎn)品添加失?。∈聞?wù)回滾");
jsonObject.put("success", false);
throw new RuntimeException();
}
int product_id = lastIDService.selectLastID();
logger.info("添加成功!,新增產(chǎn)品的ID值為:{}", product_id);
JSONObject object = JSON.parseObject(propertyJson);
Set<String> propertyIdSet = object.keySet();
if (propertyIdSet.size() > 0) {
logger.info("整合產(chǎn)品子信息-產(chǎn)品屬性");
List<PropertyValue> propertyValueList = new ArrayList<>(5);
for (String key : propertyIdSet) {
String value = object.getString(key);
PropertyValue propertyValue = new PropertyValue()
.setPropertyValue_value(value)
.setPropertyValue_property(new Property().setProperty_id(Integer.valueOf(key)))
.setPropertyValue_product(new Product().setProduct_id(product_id));
propertyValueList.add(propertyValue);
}
logger.info("共有{}條產(chǎn)品屬性數(shù)據(jù)", propertyValueList.size());
yn = propertyValueService.addList(propertyValueList);
if (yn) {
logger.info("產(chǎn)品屬性添加成功!");
} else {
logger.warn("產(chǎn)品屬性添加失??!事務(wù)回滾");
jsonObject.put("success", false);
throw new RuntimeException();
}
}
if (productSingleImageList != null && productSingleImageList.length > 0) {
logger.info("整合產(chǎn)品子信息-產(chǎn)品預(yù)覽圖片");
List<ProductImage> productImageList = new ArrayList<>(5);
for (String imageName : productSingleImageList) {
productImageList.add(new ProductImage()
.setProductImage_type((byte) 0)
.setProductImage_src(imageName.substring(imageName.lastIndexOf("/") + 1))
.setProductImage_product(new Product().setProduct_id(product_id))
);
}
logger.info("共有{}條產(chǎn)品預(yù)覽圖片數(shù)據(jù)", productImageList.size());
yn = productImageService.addList(productImageList);
if (yn) {
logger.info("產(chǎn)品預(yù)覽圖片添加成功!");
} else {
logger.warn("產(chǎn)品預(yù)覽圖片添加失?。∈聞?wù)回滾");
jsonObject.put("success", false);
throw new RuntimeException();
}
}
if (productDetailsImageList != null && productDetailsImageList.length > 0) {
logger.info("整合產(chǎn)品子信息-產(chǎn)品詳情圖片");
List<ProductImage> productImageList = new ArrayList<>(5);
for (String imageName : productDetailsImageList) {
productImageList.add(new ProductImage()
.setProductImage_type((byte) 1)
.setProductImage_src(imageName.substring(imageName.lastIndexOf("/") + 1))
.setProductImage_product(new Product().setProduct_id(product_id))
);
}
logger.info("共有{}條產(chǎn)品詳情圖片數(shù)據(jù)", productImageList.size());
yn = productImageService.addList(productImageList);
if (yn) {
logger.info("產(chǎn)品詳情圖片添加成功!");
} else {
logger.warn("產(chǎn)品詳情圖片添加失敗!事務(wù)回滾");
jsonObject.put("success", false);
throw new RuntimeException();
}
}
logger.info("產(chǎn)品信息及其子信息添加成功!");
jsonObject.put("success", true);
jsonObject.put("product_id", product_id);
return jsonObject.toJSONString();
}
//更新產(chǎn)品信息-ajax
@ResponseBody
@RequestMapping(value = "admin/product/{product_id}", method = RequestMethod.PUT, produces = "application/json;charset=utf-8")
public String updateProduct(@RequestParam String product_name/* 產(chǎn)品名稱(chēng) */,
@RequestParam String product_title/* 產(chǎn)品標(biāo)題 */,
@RequestParam Integer product_category_id/* 產(chǎn)品類(lèi)型ID */,
@RequestParam Double product_sale_price/* 產(chǎn)品最低價(jià) */,
@RequestParam Double product_price/* 產(chǎn)品最高價(jià) */,
@RequestParam Byte product_isEnabled/* 產(chǎn)品狀態(tài) */,
@RequestParam String propertyAddJson/* 產(chǎn)品添加屬性JSON */,
@RequestParam String propertyUpdateJson/* 產(chǎn)品更新屬性JSON */,
@RequestParam(required = false) Integer[] propertyDeleteList/* 產(chǎn)品刪除屬性ID數(shù)組 */,
@RequestParam(required = false) String[] productSingleImageList/*產(chǎn)品預(yù)覽圖片名稱(chēng)數(shù)組*/,
@RequestParam(required = false) String[] productDetailsImageList/*產(chǎn)品詳情圖片名稱(chēng)數(shù)組*/,
@PathVariable("product_id") Integer product_id/* 產(chǎn)品ID */) {
JSONObject jsonObject = new JSONObject();
logger.info("整合產(chǎn)品信息");
Product product = new Product()
.setProduct_id(product_id)
.setProduct_name(product_name)
.setProduct_title(product_title)
.setProduct_category(new Category().setCategory_id(product_category_id))
.setProduct_sale_price(product_sale_price)
.setProduct_price(product_price)
.setProduct_isEnabled(product_isEnabled)
.setProduct_create_date(new Date());
logger.info("更新產(chǎn)品信息,產(chǎn)品ID值為:{}", product_id);
boolean yn = productService.update(product);
if (!yn) {
logger.info("產(chǎn)品信息更新失敗!事務(wù)回滾");
jsonObject.put("success", false);
throw new RuntimeException();
}
logger.info("產(chǎn)品信息更新成功!");
JSONObject object = JSON.parseObject(propertyAddJson);
Set<String> propertyIdSet = object.keySet();
if (propertyIdSet.size() > 0) {
logger.info("整合產(chǎn)品子信息-需要添加的產(chǎn)品屬性");
List<PropertyValue> propertyValueList = new ArrayList<>(5);
for (String key : propertyIdSet) {
String value = object.getString(key);
PropertyValue propertyValue = new PropertyValue()
.setPropertyValue_value(value)
.setPropertyValue_property(new Property().setProperty_id(Integer.valueOf(key)))
.setPropertyValue_product(product);
propertyValueList.add(propertyValue);
}
logger.info("共有{}條需要添加的產(chǎn)品屬性數(shù)據(jù)", propertyValueList.size());
yn = propertyValueService.addList(propertyValueList);
if (yn) {
logger.info("產(chǎn)品屬性添加成功!");
} else {
logger.warn("產(chǎn)品屬性添加失敗!事務(wù)回滾");
jsonObject.put("success", false);
throw new RuntimeException();
}
}
object = JSON.parseObject(propertyUpdateJson);
propertyIdSet = object.keySet();
if (propertyIdSet.size() > 0) {
logger.info("整合產(chǎn)品子信息-需要更新的產(chǎn)品屬性");
List<PropertyValue> propertyValueList = new ArrayList<>(5);
for (String key : propertyIdSet) {
String value = object.getString(key);
PropertyValue propertyValue = new PropertyValue()
.setPropertyValue_value(value)
.setPropertyValue_id(Integer.valueOf(key));
propertyValueList.add(propertyValue);
}
logger.info("共有{}條需要更新的產(chǎn)品屬性數(shù)據(jù)", propertyValueList.size());
for (int i = 0; i < propertyValueList.size(); i++) {
logger.info("正在更新第{}條,共{}條", i + 1, propertyValueList.size());
yn = propertyValueService.update(propertyValueList.get(i));
if (yn) {
logger.info("產(chǎn)品屬性更新成功!");
} else {
logger.warn("產(chǎn)品屬性更新失敗!事務(wù)回滾");
jsonObject.put("success", false);
throw new RuntimeException();
}
}
}
if (propertyDeleteList != null && propertyDeleteList.length > 0) {
logger.info("整合產(chǎn)品子信息-需要?jiǎng)h除的產(chǎn)品屬性");
logger.info("共有{}條需要?jiǎng)h除的產(chǎn)品屬性數(shù)據(jù)", propertyDeleteList.length);
yn = propertyValueService.deleteList(propertyDeleteList);
if (yn) {
logger.info("產(chǎn)品屬性刪除成功!");
} else {
logger.warn("產(chǎn)品屬性刪除失敗!事務(wù)回滾");
jsonObject.put("success", false);
throw new RuntimeException();
}
}
if (productSingleImageList != null && productSingleImageList.length > 0) {
logger.info("整合產(chǎn)品子信息-產(chǎn)品預(yù)覽圖片");
List<ProductImage> productImageList = new ArrayList<>(5);
for (String imageName : productSingleImageList) {
productImageList.add(new ProductImage()
.setProductImage_type((byte) 0)
.setProductImage_src(imageName.substring(imageName.lastIndexOf("/") + 1))
.setProductImage_product(product)
);
}
logger.info("共有{}條產(chǎn)品預(yù)覽圖片數(shù)據(jù)", productImageList.size());
yn = productImageService.addList(productImageList);
if (yn) {
logger.info("產(chǎn)品預(yù)覽圖片添加成功!");
} else {
logger.warn("產(chǎn)品預(yù)覽圖片添加失??!事務(wù)回滾");
jsonObject.put("success", false);
throw new RuntimeException();
}
}
if (productDetailsImageList != null && productDetailsImageList.length > 0) {
logger.info("整合產(chǎn)品子信息-產(chǎn)品詳情圖片");
List<ProductImage> productImageList = new ArrayList<>(5);
for (String imageName : productDetailsImageList) {
productImageList.add(new ProductImage()
.setProductImage_type((byte) 1)
.setProductImage_src(imageName.substring(imageName.lastIndexOf("/") + 1))
.setProductImage_product(product)
);
}
logger.info("共有{}條產(chǎn)品詳情圖片數(shù)據(jù)", productImageList.size());
yn = productImageService.addList(productImageList);
if (yn) {
logger.info("產(chǎn)品詳情圖片添加成功!");
} else {
logger.warn("產(chǎn)品詳情圖片添加失??!事務(wù)回滾");
jsonObject.put("success", false);
throw new RuntimeException();
}
}
jsonObject.put("success", true);
jsonObject.put("product_id", product_id);
return jsonObject.toJSONString();
}
//按條件查詢(xún)產(chǎn)品-ajax
@ResponseBody
@RequestMapping(value = "admin/product/{index}/{count}", method = RequestMethod.GET, produces = "application/json;charset=utf-8")
public String getProductBySearch(@RequestParam(required = false) String product_name/* 產(chǎn)品名稱(chēng) */,
@RequestParam(required = false) Integer category_id/* 產(chǎn)品類(lèi)型ID */,
@RequestParam(required = false) Double product_sale_price/* 產(chǎn)品最低價(jià) */,
@RequestParam(required = false) Double product_price/* 產(chǎn)品最高價(jià) */,
@RequestParam(required = false) Byte[] product_isEnabled_array/* 產(chǎn)品狀態(tài)數(shù)組 */,
@RequestParam(required = false) String orderBy/* 排序字段 */,
@RequestParam(required = false,defaultValue = "true") Boolean isDesc/* 是否倒序 */,
@PathVariable Integer index/* 頁(yè)數(shù) */,
@PathVariable Integer count/* 行數(shù) */) throws UnsupportedEncodingException {
//移除不必要條件
if (product_isEnabled_array != null && (product_isEnabled_array.length <= 0 || product_isEnabled_array.length >=3)) {
product_isEnabled_array = null;
}
if (category_id != null && category_id == 0) {
category_id = null;
}
if (product_name != null) {
//如果為非空字符串則解決中文亂碼:URLDecoder.decode(String,"UTF-8");
product_name = "".equals(product_name) ? null : URLDecoder.decode(product_name, "UTF-8");
}
if (orderBy != null && "".equals(orderBy)) {
orderBy = null;
}
//封裝查詢(xún)條件
Product product = new Product()
.setProduct_name(product_name)
.setProduct_category(new Category().setCategory_id(category_id))
.setProduct_price(product_price)
.setProduct_sale_price(product_sale_price);
OrderUtil orderUtil = null;
if (orderBy != null) {
logger.info("根據(jù){}排序,是否倒序:{}",orderBy,isDesc);
orderUtil = new OrderUtil(orderBy, isDesc);
}
JSONObject object = new JSONObject();
logger.info("按條件獲取第{}頁(yè)的{}條產(chǎn)品", index + 1, count);
PageUtil pageUtil = new PageUtil(index, count);
List<Product> productList = productService.getList(product, product_isEnabled_array, orderUtil, pageUtil);
object.put("productList", JSONArray.parseArray(JSON.toJSONString(productList)));
logger.info("按條件獲取產(chǎn)品總數(shù)量");
Integer productCount = productService.getTotal(product, product_isEnabled_array);
object.put("productCount", productCount);
logger.info("獲取分頁(yè)信息");
pageUtil.setTotal(productCount);
object.put("totalPage", pageUtil.getTotalPage());
object.put("pageUtil", pageUtil);
return object.toJSONString();
}
//按類(lèi)型ID查詢(xún)屬性-ajax
@ResponseBody
@RequestMapping(value = "admin/property/type/{property_category_id}", method = RequestMethod.GET,produces = "application/json;charset=utf-8")
public String getPropertyByCategoryId(@PathVariable Integer property_category_id/* 屬性所屬類(lèi)型ID*/){
//封裝查詢(xún)條件
Category category = new Category()
.setCategory_id(property_category_id);
JSONObject object = new JSONObject();
logger.info("按類(lèi)型獲取屬性列表,類(lèi)型ID:{}",property_category_id);
List<Property> propertyList = propertyService.getList(new Property().setProperty_category(category),null);
object.put("propertyList",JSONArray.parseArray(JSON.toJSONString(propertyList)));
return object.toJSONString();
}
//按ID刪除產(chǎn)品圖片并返回最新結(jié)果-ajax
@ResponseBody
@RequestMapping(value = "admin/productImage/{productImage_id}",method = RequestMethod.DELETE,produces = "application/json;charset=utf-8")
public String deleteProductImageById(@PathVariable Integer productImage_id/* 產(chǎn)品圖片ID */){
JSONObject object = new JSONObject();
logger.info("獲取productImage_id為{}的產(chǎn)品圖片信息",productImage_id);
ProductImage productImage = productImageService.get(productImage_id);
logger.info("刪除產(chǎn)品圖片");
Boolean yn = productImageService.deleteList(new Integer[]{productImage_id});
if (yn) {
logger.info("刪除圖片成功!");
object.put("success", true);
} else {
logger.warn("刪除圖片失??!事務(wù)回滾");
object.put("success", false);
throw new RuntimeException();
}
return object.toJSONString();
}
//上傳產(chǎn)品圖片-ajax
@ResponseBody
@RequestMapping(value = "admin/uploadProductImage", method = RequestMethod.POST, produces = "application/json;charset=utf-8")
public String uploadProductImage(@RequestParam MultipartFile file, @RequestParam String imageType, HttpSession session) {
String originalFileName = file.getOriginalFilename();
logger.info("獲取圖片原始文件名:{}", originalFileName);
String extension = originalFileName.substring(originalFileName.lastIndexOf('.'));
String filePath;
String fileName = UUID.randomUUID() + extension;
if ("single".equals(imageType)) {
filePath = session.getServletContext().getRealPath("/") + "res/images/item/productSinglePicture/" + fileName;
} else {
filePath = session.getServletContext().getRealPath("/") + "res/images/item/productDetailsPicture/" + 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();
}
}到此這篇關(guān)于Java實(shí)戰(zhàn)之仿天貓商城系統(tǒng)的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Java天貓商城系統(tǒng)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Java 仿天貓服裝商城系統(tǒng)的實(shí)現(xiàn)流程
- Java 實(shí)戰(zhàn)項(xiàng)目錘煉之仿天貓網(wǎng)上商城的實(shí)現(xiàn)流程
- Java畢業(yè)設(shè)計(jì)實(shí)戰(zhàn)之寵物醫(yī)院與商城一體的系統(tǒng)的實(shí)現(xiàn)
- Java畢業(yè)設(shè)計(jì)實(shí)戰(zhàn)之仿小米電子產(chǎn)品售賣(mài)商城系統(tǒng)的實(shí)現(xiàn)
- Java畢業(yè)設(shè)計(jì)實(shí)戰(zhàn)項(xiàng)目之在線(xiàn)服裝銷(xiāo)售商城系統(tǒng)的實(shí)現(xiàn)流程
- Java實(shí)戰(zhàn)玩具商城的前臺(tái)與后臺(tái)實(shí)現(xiàn)流程
- Java女裝商城系統(tǒng)的實(shí)現(xiàn)流程
相關(guān)文章
spring boot 防止重復(fù)提交實(shí)現(xiàn)方法詳解
這篇文章主要介紹了spring boot 防止重復(fù)提交實(shí)現(xiàn)方法,結(jié)合實(shí)例形式詳細(xì)分析了spring boot 防止重復(fù)提交具體配置、實(shí)現(xiàn)方法及操作注意事項(xiàng),需要的朋友可以參考下2019-11-11
Spring Boot 項(xiàng)目做性能監(jiān)控的操作流程
這篇文章主要介紹了Spring Boot 項(xiàng)目如何做性能監(jiān)控,本文通過(guò)實(shí)例代碼圖文相結(jié)合給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-07-07
SpringBoot使用classfinal-maven-plugin插件加密Jar包的示例代碼
這篇文章給大家介紹了SpringBoot使用classfinal-maven-plugin插件加密Jar包的實(shí)例,文中通過(guò)代碼示例和圖文講解的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-02-02
SpringMVC結(jié)合ajaxfileupload.js實(shí)現(xiàn)文件無(wú)刷新上傳
這篇文章主要介紹了SpringMVC結(jié)合ajaxfileupload.js實(shí)現(xiàn)文件無(wú)刷新上傳,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-10-10
Java入門(mén)絆腳石之Override和Overload的區(qū)別詳解
重寫(xiě)是子類(lèi)對(duì)父類(lèi)的允許訪問(wèn)的方法的實(shí)現(xiàn)過(guò)程進(jìn)行重新編寫(xiě), 返回值和形參都不能改變。即外殼不變,核心重寫(xiě)!重寫(xiě)的好處在于子類(lèi)可以根據(jù)需要,定義特定于自己的行為。重載是在一個(gè)類(lèi)里面,方法名字相同,而參數(shù)不同。返回類(lèi)型可以相同也可以不同2021-10-10
Java?System#exit無(wú)法退出程序的問(wèn)題及解決
這篇文章主要介紹了Java?System#exit無(wú)法退出程序的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04
Mybatis操作數(shù)據(jù)時(shí)出現(xiàn):java.sql.SQLSyntaxErrorException:?Unknown?c
這篇文章主要介紹了Mybatis操作數(shù)據(jù)時(shí)出現(xiàn):java.sql.SQLSyntaxErrorException:?Unknown?column?'XXX'?in?'field?list',需要的朋友可以參考下2023-04-04

