作者主页:夜未央5788
简介:Java领域优质创作者、Java项目、学习资料、技术互助
文末获取源码
项目介绍
本项目分为前后台,有管理员与用户两种角色;
管理员角色包含以下功能:
管理员登录,商品分类管理,商品管理,商品属性管理,商品参数管理,订单管理,退款管理,退货管理,会员等级管理,客户信息管理,评论管理,文章分类管理,公告管理,文章管理,滚动图片管理,广告管理,热门查询管理,查询订单销售,查询商品销售,用户管理,角色管理,资源管理,修改密码,区域管理,配送方式管理,查看系统设置,缓存管理,查询到货通知等功能。
用户角色包含以下功能:
用户登录,查看首页,查看商品详情,查看购物车,提交订单,修改个人信息,修改密码,查看我的订单,添加配送地址,查看收藏夹等功能。
环境需要
1.运行环境:最好是java jdk 1.8,我们在这个平台上运行的。其他版本理论上也可以。
2.IDE环境:Eclipse;注:本项目目前仅支持Eclipse,暂不支持IDEA;
3.tomcat环境:Tomcat 7.x,8.x,9.x版本均可
4.硬件环境:windows 7/8/10 1G内存以上;或者 Mac OS;
5.数据库:MySql 5.7版本;
6.是否Maven项目:否;
技术栈
1. 后端:Spring+SpringMVC+Mbytes
2. 前端:Freemarker+css+javascript+bootstrap+jQuery
使用说明
1. 使用Navicat或者其它工具,在mysql中创建对应名称的数据库,并导入项目的sql文件;
2. 使用Eclipse导入项目,将项目中src目录下的conf.properties配置文件中的数据库配置改为自己的配置;
3. 运行项目,在浏览器中输入localhost:8080/ssm_zxbookshop
用户账号/密码: user/123456
管理员账号/密码:admin/admin
运行截图
用户角色
管理员角色
相关代码
BaseController
package net.jeeshop.web.action;
import net.jeeshop.core.Services;
import net.jeeshop.core.dao.page.PagerModel;
import net.jeeshop.core.front.SystemManager;
import net.jeeshop.web.util.RequestHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* Created by dylan on 15-2-2.
* @author dylan
*/
public abstract class BaseController<E extends PagerModel> {
protected Logger logger = LoggerFactory.getLogger(getClass());
protected String page_toList = null;
protected String page_toEdit = null;
protected String page_toAdd = null;
public abstract Services<E> getService();
@Autowired
protected SystemManager systemManager;
/**
* 后台左边导航菜单的初始化查询方法
*/
protected void initPageSelect() {
logger.error("initPageSelect..init=n!");
}
/**
* 初始化查询的时候,会清除所有的查询参数(所以在e中的),但可以设置不在e中的参数,然后在此方法中进行e.setXxx(参数)的方式进行保留。
*/
protected void setParamWhenInitQuery(E e) {
//BaseAction 的子类如有初始化页面的时候进行相关查询 ,则可以实现此方法。
}
/**
* 公共的分页方法
*
* @return
* @throws Exception
*/
@RequestMapping("selectList")
public String selectList(HttpServletRequest request, @ModelAttribute("e") E e) throws Exception {
/**
* 由于prepare方法不具备一致性,加此代码解决init=y查询的时候条件不被清除干净的BUG
*/
this.initPageSelect();
setParamWhenInitQuery(e);
int offset = 0;//分页偏移量
if (request.getParameter("pager.offset") != null) {
offset = Integer.parseInt(request.getParameter("pager.offset"));
}
if (offset < 0) offset = 0;
e.setOffset(offset);
PagerModel pager = getService().selectPageList(e);
if (pager == null) {
pager = new PagerModel();
}
// 计算总页数
pager.setPagerSize((pager.getTotal() + pager.getPageSize() - 1) / pager.getPageSize());
selectListAfter(pager);
request.setAttribute("pager", pager);
return page_toList;
}
@RequestMapping("toEdit")
public String toEdit(@ModelAttribute("e") E e, ModelMap model) throws Exception {
e = getService().selectOne(e);
// if(e==null || StringUtils.isBlank(e.getId())){
// throw new NullPointerException("");
// }
model.addAttribute("e", e);
return page_toEdit;
}
@RequestMapping("toAdd")
public String toAdd(@ModelAttribute("e") E e, ModelMap model) throws Exception {
e.clear();
return page_toAdd;
}
/**
* 子类必须要实现的方法当分页查询后.
* 解决了用户先点击新增按钮转到新增页面,然后点击返回按钮返回后,再点分页控件出错的BUG.
* 原因是分页查询后未将pageUrl重新设置为正确的URL所致
*/
protected void selectListAfter(PagerModel pager) {
pager.setPagerUrl("selectList");
}
/**
* 返回到查询页面
*
* @return
* @throws Exception
*/
@RequestMapping("back")
public String back(@ModelAttribute("e") E e, ModelMap model) throws Exception {
return selectList(RequestHolder.getRequest(), e);
}
/**
* 公共的批量删除数据的方法,子类可以通过重写此方法实现个性化的需求。
*
* @return
* @throws Exception
*/
@RequestMapping(value = "deletes", method = RequestMethod.POST)
public String deletes(HttpServletRequest request, String[] ids, @ModelAttribute("e") E e, RedirectAttributes flushAttrs) throws Exception {
// User user = (User) getSession().getAttribute(Global.USER_INFO);
// if(user==null){
// throw new NullPointerException();
// }
// if(user.getDbPrivilegeMap()!=null && user.getDbPrivilegeMap().size()>0){
// if(user.getDbPrivilegeMap().get(Container.db_privilege_delete)==null){
// throw new PrivilegeException(Container.db_privilege_delete_error);
// }
// }
getService().deletes(ids);
addMessage(flushAttrs, "操作成功!");
return "redirect:selectList";
}
/**
* 公共的更新数据的方法,子类可以通过重写此方法实现个性化的需求。
*
* @return
* @throws Exception
*/
@RequestMapping(value = "update", method = RequestMethod.POST)
public String update(HttpServletRequest request, @ModelAttribute("e") E e, RedirectAttributes flushAttrs) throws Exception {
// User user = (User) getSession().getAttribute(Global.USER_INFO);
// if(user==null){
// throw new NullPointerException();
// }
// if(user.getDbPrivilegeMap()!=null && user.getDbPrivilegeMap().size()>0){
// if(user.getDbPrivilegeMap().get(Container.db_privilege_update)==null){
// throw new PrivilegeException(Container.db_privilege_update_error);
// }
// }
getService().update(e);
insertAfter(e);
addMessage(flushAttrs, "操作成功!");
return "redirect:selectList";
}
/**
* insert之后,selectList之前执行的动作,一般需要清除添加的E,否则查询会按照E的条件进行查询.
* 部分情况下需要保留某些字段,可以选择不清除
*
* @param e
*/
protected void insertAfter(E e){
}
/**
* 公共的插入数据方法,子类可以通过重写此方法实现个性化的需求。
*
* @return
* @throws Exception
*/
@RequestMapping(value = "insert",method = RequestMethod.POST)
public String insert(HttpServletRequest request, @ModelAttribute("e") E e, RedirectAttributes flushAttrs) throws Exception {
// User user = (User) getSession().getAttribute(Global.USER_INFO);
// if(user==null){
// throw new NullPointerException();
// }
// if(user.getDbPrivilegeMap()!=null && user.getDbPrivilegeMap().size()>0){
// if(user.getDbPrivilegeMap().get(Container.db_privilege_insert)==null){
// throw new PrivilegeException(Container.db_privilege_insert_error);
// }
// }
getService().insert(e);
insertAfter(e);
addMessage(flushAttrs, "操作成功!");
return "redirect:selectList";
}
/**
* 跳转到编辑页面
*
* @return
* @throws Exception
*/
// @RequestMapping("toEdit")
// public String toEdit(@ModelAttribute("e") E e, ModelMap model) throws Exception {
// e = getService().selectOne(e);
if(e==null || StringUtils.isBlank(e.getId())){
throw new NullPointerException("");
}
// return toEdit;
// }
// @RequestMapping("toAdd")
// public String toAdd(@ModelAttribute("e") E e, ModelMap model) throws Exception {
// e.clear();
// return toAdd;
// }
@RequestMapping("loadData")
@ResponseBody
public PagerModel loadData(HttpServletRequest request, E e){
int offset = 0;
int pageSize = 10;
if (request.getParameter("start") != null) {
offset = Integer
.parseInt(request.getParameter("start"));
}
if (request.getParameter("length") != null) {
pageSize = Integer
.parseInt(request.getParameter("length"));
}
if (offset < 0)
offset = 0;
if(pageSize < 0){
pageSize = 10;
}
e.setOffset(offset);
e.setPageSize(pageSize);
PagerModel pager = getService().selectPageList(e);
pager.setRecordsTotal(pager.getTotal());
pager.setRecordsFiltered(pager.getTotal());
return pager;
}
protected void addMessage(ModelMap modelMap, String message) {
modelMap.addAttribute("message", message);
}
protected void addWarning(ModelMap modelMap, String warning) {
modelMap.addAttribute("warning", warning);
}
protected void addError(ModelMap modelMap, String warning) {
modelMap.addAttribute("errorMsg", warning);
}
protected void addMessage(RedirectAttributes flushAttrs, String message) {
flushAttrs.addFlashAttribute("message", message);
}
protected void addWarning(RedirectAttributes flushAttrs, String warning) {
flushAttrs.addFlashAttribute("warning", warning);
}
protected void addError(RedirectAttributes flushAttrs, String warning) {
flushAttrs.addFlashAttribute("errorMsg", warning);
}
}
CommonController
package net.jeeshop.web.action;
import net.jeeshop.core.front.SystemManager;
import net.jeeshop.core.util.ImageUtils;
import net.jeeshop.services.common.SystemSetting;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
/**
* @author dylan
* @date 16/2/15 16:29
* Email: dinguangx@163.com
*/
@Controller
@RequestMapping("/common")
public class CommonController {
private Logger logger = LoggerFactory.getLogger(getClass());
@RequestMapping("uploadify")
@ResponseBody
public String uploadify(@RequestParam("Filedata")MultipartFile filedata,
@RequestParam(required = false, defaultValue = "1")String thumbnail) {
boolean createThumbnail = "1".equals(thumbnail);
SystemSetting systemSetting = SystemManager.getInstance().getSystemSetting();
//文件保存目录路径
String savePath = SystemManager.getInstance().getProperty("file.upload.path");
//文件保存目录URL
String saveUrl = systemSetting.getImageRootPath();
//定义允许上传的文件扩展名
HashMap<String, String> extMap = new HashMap<String, String>();
extMap.put("image", "gif,jpg,jpeg,png,bmp");
extMap.put("flash", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");
extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");
//最大文件大小
long maxSize = 1000000;
//检查目录
File uploadDir = new File(savePath);
if (!uploadDir.isDirectory()) {
return (getError("上传目录不存在。"));
}
//检查目录写权限
if (!uploadDir.canWrite()) {
return (getError("上传目录没有写权限。"));
}
String dirName = "image";
if (!extMap.containsKey(dirName)) {
return (getError("目录名不正确。"));
}
//创建文件夹
savePath += dirName + "/";
saveUrl += dirName + "/";
String relativePath = dirName + "/";
File saveDirFile = new File(savePath);
if (!saveDirFile.exists()) {
saveDirFile.mkdirs();
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String ymd = sdf.format(new Date());
savePath += ymd + "/";
saveUrl += ymd + "/";
relativePath += ymd + "/";
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
String fileName = filedata.getOriginalFilename();
//检查扩展名
String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
return (getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式。"));
}
String newFileName1 = null;//小图
String newFileName2 = null;//中图
String newFileName3 = null;//大图 ,也是原图
String newFileName0 = String.valueOf(System.currentTimeMillis());
logger.debug("newFileName0=" + newFileName0);
newFileName1 = newFileName0 + "_1";
newFileName2 = newFileName0 + "_2";
newFileName3 = newFileName0 + "_3." + fileExt;
logger.debug("newFileName1=" + newFileName1 + ",newFileName2=" + newFileName2 + ",newFileName3=" + newFileName3);
File uploadedFile3 = new File(savePath, newFileName3);
try {
filedata.transferTo(uploadedFile3);
if(createThumbnail) {
File uploadedFile1 = new File(savePath, newFileName1 + "." + fileExt);
File uploadedFile2 = new File(savePath, newFileName2 + "." + fileExt);
ImageUtils.ratioZoom2(uploadedFile3, uploadedFile1, Double.valueOf(SystemManager.getInstance().getProperty("product_image_1_w")));
ImageUtils.ratioZoom2(uploadedFile3, uploadedFile2, Double.valueOf(SystemManager.getInstance().getProperty("product_image_2_w")));
}
} catch (Exception e) {
logger.error("上传文件异常:" + e.getMessage());
return (getError("上传文件失败。"));
}
JSONObject obj = new JSONObject();
obj.put("error", 0);
obj.put("filePath", relativePath + newFileName3);
return (obj.toString());
}
private String getError(String msg) {
JSONObject obj = new JSONObject();
obj.put("error", 1);
obj.put("msg", msg);
return (obj.toString());
}
}
ForwardController
package net.jeeshop.web.action;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* Created by dylan on 15-1-18.
*/
@Controller
@RequestMapping("forward")
public class ForwardController {
private String p = "/common/404";
@RequestMapping
public String forward(@RequestParam("p")String page){
if(StringUtils.isBlank(page)){
return p;
}
return page.trim();
}
}
购物车
package net.jeeshop.web.action.front.cart;
import com.alibaba.fastjson.JSON;
import net.jeeshop.core.FrontContainer;
import net.jeeshop.core.Services;
import net.jeeshop.core.front.SystemManager;
import net.jeeshop.services.front.account.bean.Account;
import net.jeeshop.services.front.address.AddressService;
import net.jeeshop.services.front.product.ProductService;
import net.jeeshop.services.front.product.bean.Product;
import net.jeeshop.services.front.product.bean.ProductStockInfo;
import net.jeeshop.services.manage.activity.bean.Activity;
import net.jeeshop.services.manage.spec.SpecService;
import net.jeeshop.services.manage.spec.bean.Spec;
import net.jeeshop.web.action.front.FrontBaseController;
import net.jeeshop.web.action.front.orders.CartInfo;
import net.jeeshop.web.util.RequestHolder;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* 购物车
*
* @author huangf
*
*/
@Controller("frontCartAction")
@RequestMapping("cart")
public class CartAction extends FrontBaseController<CartInfo> {
private static final long serialVersionUID = 1L;
private static final Logger logger = LoggerFactory.getLogger(CartAction.class);
@Autowired
private ProductService productService;
@Autowired
private AddressService addressService;
@Autowired
private SpecService specService;
@Override
public Services<CartInfo> getService() {
return null;
}
/**
* 查看购物车
* @return
*/
@RequestMapping("cart")
public String cart(ModelMap model){
logger.error("AccountAction.cart查看购物车...");
// Account acc = (Account) getSession().getAttribute(FrontContainer.USER_INFO);
// if (acc == null || StringUtils.isBlank(acc.getAccount())) {
// return "toLogin";
// }
List<Product> productList = new ArrayList<Product>();
CartInfo cartInfo = getMyCart();
if(cartInfo!=null){
productList = cartInfo.getProductList();
} else {
cartInfo = new CartInfo();
}
model.addAttribute("cartInfo", cartInfo);
model.addAttribute("productList", productList);
return "cart";
// String addCart = getRequest().getParameter("addCart");
// CartInfo cartInfo = (CartInfo) getSession().getAttribute(FrontContainer.myCart);
// if(cartInfo==null){
// cartInfo = new CartInfo();
// }
// getSession().setAttribute(FrontContainer.myCart,cartInfo);
// logger.error("===addCart="+(addCart!=null && addCart.equals("1")));
// if(addCart!=null && addCart.equals("1")){
// String productID = getE().getId();
// if(StringUtils.isEmpty(productID)){
// //查询购物车
// return "cart";
// }
//
// if(cartInfo==null){
// cartInfo = new CartInfo();
// getSession().setAttribute(FrontContainer.myCart, cartInfo);
// }
// int inputBuyNum = Integer.valueOf(getRequest().getParameter("inputBuyNum"));
// if(inputBuyNum<=0){
// throw new NullPointerException();
// }
// //检查指定的产品是否已购买到购物车,购买了则数量++,否则查询后添加到购物车
// boolean exists = false;
// for(int i=0;i<cartInfo.getProductList().size();i++){
// Product p = cartInfo.getProductList().get(i);
// if(p.getId().equals(productID)){
// p.setBuyCount(p.getBuyCount()+inputBuyNum);
// exists = true;
// }
// }
// if(!exists){
// //添加产品到购物车
// System.out.println("id="+productID);
getE().clear();
// Product pp = new Product();
// pp.setId(productID);
// pp.setStatus(1);
// pp = productService.selectOne(pp);
// if(pp==null){
// throw new NullPointerException("根据商品ID="+productID+"查询不到指定的商品信息。");
// }
// pp.setBuyCount(inputBuyNum);
//
// cartInfo.getProductList().add(pp);
// }
// cartInfo.setAmount(cartInfo.cacl());
// getE().clear();
//
// }
//
// //加载配送信息
// Address add = new Address();
// add.setAccount(acc.getAccount());
// List<Address> addressList = addressService.selectList(add);
// cartInfo.setAddressList(addressList);
// if(addressList!=null && addressList.size()>0){
boolean exist = false;
// for(int i=0;i<addressList.size();i++){
// Address addItem = addressList.get(i);
// if(StringUtils.isNotBlank(addItem.getIsdefault()) && addItem.getIsdefault().equals("y")){
// cartInfo.setDefaultAddessID(addItem.getId());
// break;
// }
// }
// }
// logger.error("cartInfo="+cartInfo);
// return "cart";
}
/**
* 从购物车中删除指定的产品
* @return
*/
@RequestMapping(value = "delete", method = RequestMethod.POST)
public String delete(ModelMap model, String id){
if(StringUtils.isBlank(id)){
throw new NullPointerException("非法请求!");
}
CartInfo cartInfo = getMyCart();
if(cartInfo==null){
//会话超时,转到登陆页面
return page_toLoginRedirect;
}
for(Iterator<Product> it = cartInfo.getProductList().iterator();it.hasNext();){
Product p = it.next();
if(p.getId().equals(id)){
it.remove();
//重新计算总支付金额
// cartInfo.setAmount(cartInfo.totalCacl());
cartInfo.totalCacl();
break;
}
}
return "redirect:/cart/cart.html";
}
DecimalFormat df = new DecimalFormat("0.00");
/**
* 加入购物车,不对金额进行任何的运算。金额的运算在方法CartAction.notifyCart
* @return
* @throws IOException
*/
@RequestMapping("addToCart")
@ResponseBody
public String addToCart(ModelMap model) throws IOException{
// Account acc = (Account) getSession().getAttribute(FrontContainer.USER_INFO);
// if (acc == null || StringUtils.isBlank(acc.getAccount())) {
// super.write("1");//需要登录
// return null;
// }
logger.info("ProductAction.cart...");
HttpServletRequest request = RequestHolder.getRequest();
String productID = request.getParameter("productID");//商品ID
int buyCount = Integer.valueOf(request.getParameter("buyCount"));//购买数量
String buySpecID = request.getParameter("buySpecID");//选中的规格ID
if(StringUtils.isEmpty(productID) || buyCount<=0){
throw new NullPointerException("参数错误!");
}
/**
* 检查内存库存是否已超卖,如果超库存不足,则提醒用户
*/
ProductStockInfo momeryStockInfo = SystemManager.getInstance().getProductStockMap().get(productID);
if(momeryStockInfo==null){
String jsonError = JSON.toJSONString(new StockErrorProduct(productID,"很抱歉,商品已下架暂时无法购买!"));
logger.info("jsonError=" + jsonError);
return (jsonError);
}
CartInfo cartInfo = getMyCart();
if(cartInfo==null){
cartInfo = new CartInfo();
}
RequestHolder.getSession().setAttribute(FrontContainer.myCart, cartInfo);
//检查指定的产品是否已购买到购物车,购买了则数量++,否则查询后添加到购物车
boolean exists = false;
for(int i=0;i<cartInfo.getProductList().size();i++){
Product p = cartInfo.getProductList().get(i);
if(p.getId().equals(productID)){
p.setBuyCount(p.getBuyCount()+buyCount);
logger.info("商品已购买,只对数量进行++,总数=" + p.getBuyCount());
if(p.getExchangeScore() > 0){
p.setTotal0("0.00");
p.setTotalExchangeScore(p.getBuyCount() * p.getExchangeScore());
}else{
p.setTotal0(df.format(p.getBuyCount() * Double.valueOf(p.getNowPrice())));
}
exists = true;
}
}
//如果购物车中部存在此商品,则添加到购物车
if(!exists){
Product product = new Product();
product.setId(productID);
// product.setStatus(1);
product = productService.selectOne(product);
if(product==null){
throw new NullPointerException();
}
/**
* 如果此商品为促销活动的商品,则按照活动规则计算商品金额
*/
if(StringUtils.isNotBlank(product.getActivityID())){
Activity activity = SystemManager.getInstance().getActivityMap().get(product.getActivityID());
if(activity==null){
String jsonError = JSON.toJSONString(new StockErrorProduct(productID,"活动可能已下架!"));
logger.error("jsonError="+jsonError);
return (jsonError);//活动可能已下架!
}else if(activity.checkActivity()){
String jsonError = JSON.toJSONString(new StockErrorProduct(productID,"活动已结束!"));
logger.error("jsonError="+jsonError);
return (jsonError);//活动已结束!
}
//检查是否符合此活动的会员等级范围
Account acc = getLoginAccount();
if(acc==null){
String jsonError = JSON.toJSONString(new StockErrorProduct(productID,"此商品为促销活动的商品,请先登陆才能购买!!"));
logger.error("jsonError="+jsonError);
return (jsonError);
}
logger.error("acc.getRank() = " + acc.getRank());
logger.error("activity.getAccountRange() = " + activity.getAccountRange());
if(activity.getAccountRange().indexOf(acc.getRank()) < 0){
String jsonError = JSON.toJSONString(new StockErrorProduct(productID,"您的会员等级不在此活动的购买范围内!"));
logger.error("jsonError="+jsonError);
return (jsonError);
}
//计算活动商品的最终结算价
product.setNowPrice(product.caclFinalPrice());
//判断如果是积分商品,则计算所需的积分
if(activity.getActivityType().equals(Activity.activity_activityType_j)){
product.setExchangeScore(activity.getExchangeScore());
}
}
product.setBuyCount(buyCount);
/**
* 加载指定商品的规格信息
*/
if(StringUtils.isNotBlank(buySpecID)){
Spec spec = specService.selectById(buySpecID);
if(spec==null){
throw new NullPointerException("根据指定的规格"+buySpecID+"查询不到任何数据!");
}
product.setBuySpecInfo(spec);
//减少以后的逻辑判断,规格的价格等同于商品的价格
product.setNowPrice(spec.getSpecPrice());
}
if(product.getExchangeScore()==0){
product.setTotal0(df.format(product.getBuyCount() * Double.valueOf(product.getNowPrice())));
}else{
product.setTotalExchangeScore(product.getBuyCount() * product.getExchangeScore());
product.setTotal0("0.00");
}
cartInfo.getProductList().add(product);
logger.error("添加商品到购物车!商品ID="+product.getId());
}
cartInfo.totalCacl();//计算购物车中商品总金额
// e.clear();
return ("0");//成功添加商品到购物车
}
/**
* 通知购物车+-商品,然后计算出总金额返回。
* @return
* @throws IOException
*/
@RequestMapping(value = "notifyCart", method = RequestMethod.POST)
@ResponseBody
public String notifyCart(ModelMap model) throws IOException{
HttpServletRequest request = RequestHolder.getRequest();
int currentBuyNumber = Integer.valueOf(request.getParameter("currentBuyNumber"));//当前购买的商品的数量
String productID = request.getParameter("productID");//+-的商品ID
logger.error("currentBuyNumber="+currentBuyNumber+",productID="+productID);
if (StringUtils.isBlank(productID) || currentBuyNumber<=0) {
throw new NullPointerException("非法请求!");
}
CartInfo cartInfo = getMyCart();
if(cartInfo==null || cartInfo.getProductList()==null || cartInfo.getProductList().size()==0){
//购物车失效,转到登陆页面
return page_toLoginRedirect;
}
// String msg = null;
CartProductInfo cartProductInfo = new CartProductInfo();
/**
* 检查购买的商品是否超出库存数
*/
ProductStockInfo stockInfo = SystemManager.getInstance().getProductStockMap().get(productID);
if(stockInfo==null){
//商品已卖完或已下架,请联系站点管理员!
logger.error("商品已卖完或已下架,请联系站点管理员或从购物车中删除!");
cartProductInfo.code = "notThisProduct";
cartProductInfo.msg = "商品已卖完或已下架,请联系站点管理员或从购物车中删除!";
return (JSON.toJSONString(cartProductInfo));
// super.write("{\"code\":\"notThisProduct\",\"msg\":\"商品已卖完或已下架,请联系站点管理员或从购物车中删除!\"}");
} else if(StringUtils.isNotBlank(stockInfo.getActivityID())){
/**
* 购买的是活动促销的商品,则检查是否超出购买的最大数量
*/
Activity activity = SystemManager.getInstance().getActivityMap().get(stockInfo.getActivityID());
if(activity==null || activity.getStatus().equals(Activity.activity_status_n)){
cartProductInfo.code = "buyMore";
cartProductInfo.msg = "此商品为促销活动的商品,最多只能购买" + activity.getMaxSellCount()+"件";
return (JSON.toJSONString(cartProductInfo));
}else if(activity.getMaxSellCount() != 0 && currentBuyNumber > activity.getMaxSellCount()){
// String msg0 = "此商品为促销活动的商品,最多只能购买" + activity.getMaxSellCount()+"件";
// msg = "{\"code\":\"buyMore\",\"msg\":\"" + msg0 + "\",\"maxStock\":\""+stockInfo.getStock()+"\"}";
cartProductInfo.code = "buyMore";
cartProductInfo.msg = "此商品为促销活动的商品,最多只能购买" + activity.getMaxSellCount()+"件";
return (JSON.toJSONString(cartProductInfo));
}
// if(activity.getActivityType().equals(Activity.activity_activityType_j)){
currentBuyNumber * activity.getExchangeScore()
// activity.sete
// }
}else{
if(stockInfo.getStock() < currentBuyNumber){
//购买的商品数超出库存数,则自动当最大库存数计算
currentBuyNumber = stockInfo.getStock();
// String msg0 = "最多只能买"+stockInfo.getStock()+"件";
// msg = "{\"code\":\"buyMore\",\"msg\":\""+msg0+"\",\"maxStock\":\""+stockInfo.getStock()+"\"}";
cartProductInfo.code = "buyMore";
cartProductInfo.msg = "最多只能买"+stockInfo.getStock()+"件";
return (JSON.toJSONString(cartProductInfo));
}
}
/**
* 计算出点击+-的这一个商品的一些信息:小计、所需积分
*/
// if(msg==null){
for(int i=0;i<cartInfo.getProductList().size();i++){
Product pro = cartInfo.getProductList().get(i);
if(pro.getId().equals(productID)){
pro.setBuyCount(currentBuyNumber);//设置指定商品购买的数量
cartInfo.totalCacl();//计算购物车中商品总金额
// msg = "{\"code\":\"ok\",\"amount\":\""+cartInfo.getAmount()+"\"}";
if(pro.getExchangeScore()==0){
pro.setTotal0(df.format(Double.valueOf(pro.getNowPrice()) * pro.getBuyCount()));
}else{
pro.setTotal0("0.00");
pro.setTotalExchangeScore(pro.getBuyCount() * pro.getExchangeScore());
}
cartProductInfo.code = "ok";
cartProductInfo.total0 = pro.getTotal0();
cartProductInfo.amount = cartInfo.getAmount();
cartProductInfo.totalExchangeScore = pro.getBuyCount() * pro.getExchangeScore();
cartProductInfo.amountExchangeScore = cartInfo.getTotalExchangeScore();
// cartProductInfo.msg = "{\"code\":\"ok\",\"amount\":\""+cartInfo.getAmount()+"\"}";
break;
}
}
// }
return (JSON.toJSONString(cartProductInfo));
}
/**
* 正式转到支付之前的最后一次检查库存
* 此方法也可以用于批量错误消息检查,比如在购物车商品列表页面,提交到支付页面的时候进行批量检查(所有商品是否都有货、是否存在超卖、是否已下架、是否活动已结束(未在指定时间内进行支付,且活动已结束))
* @return
* @throws IOException
*/
@RequestMapping("checkStockLastTime")
@ResponseBody
public String checkStockLastTime() throws IOException{
logger.error("checkStockLastTime...");
Account acc = getLoginAccount();
if(acc==null){
// throw new NullPointerException("请先登陆!");
logger.error("提示用户需要登录...");
return ("-1");//提示用户需要登录
}
StockErrorProductReturn result = new StockErrorProductReturn();
CartInfo cartInfo = getMyCart();
if(cartInfo==null){
logger.error("login..");
//session超时,转到登陆页面,让用户重新登陆下单,上次未支付的单子只能找不到了。
result.code = "login";
return (JSON.toJSONString(result).toString());
}
result.code = "result";
List<StockErrorProduct> list = new LinkedList<CartAction.StockErrorProduct>();
for(int i=0;i<cartInfo.getProductList().size();i++){
Product pro = cartInfo.getProductList().get(i);
ProductStockInfo stockInfo = SystemManager.getInstance().getProductStockMap().get(pro.getId());
if(stockInfo!=null){
if(StringUtils.isNotBlank(stockInfo.getActivityID())){
/**
* 购买的是活动促销的商品,则检查是否超出购买的最大数量
*/
Activity activity = SystemManager.getInstance().getActivityMap().get(stockInfo.getActivityID());
if(activity.getMaxSellCount() != 0 && pro.getBuyCount() > activity.getMaxSellCount()){
String msg0 = "此商品为促销活动的商品,最多只能购买" + activity.getMaxSellCount()+"件";
// msg = "{\"code\":\"buyMore\",\"msg\":\"" + msg0 + "\",\"maxStock\":\""+stockInfo.getStock()+"\"}";
list.add(new StockErrorProduct(pro.getId(),msg0));
}
//如果商品为需要积分兑换的,则检查用户账户上的积分是否足够
if(false){
acc = getLoginAccount();
if(acc==null){
throw new NullPointerException("请先登陆!");
}
//积分不足的错误提示
if(acc.getScore() < activity.getExchangeScore() * pro.getBuyCount()){
list.add(new StockErrorProduct(pro.getId(),"此商品总共所需积分:"+activity.getExchangeScore() * pro.getBuyCount() + "点,可惜您目前只有"+acc.getScore()+"积分"));
}
}
}else{
if(stockInfo.getStock()<pro.getBuyCount()){
//购物车中购买的商品超出库存数
list.add(new StockErrorProduct(pro.getId(),"最多只能购买"+stockInfo.getStock()+"个!"));
}
// if(stockInfo.getStock() < currentBuyNumber){
// //购买的商品数超出库存数,则自动当最大库存数计算
// currentBuyNumber = stockInfo.getStock();
//
// String msg0 = "最多只能买"+stockInfo.getStock()+"件";
// msg = "{\"code\":\"buyMore\",\"msg\":\""+msg0+"\",\"maxStock\":\""+stockInfo.getStock()+"\"}";
// }
}
}else{
//商品可能已经下架或售完!
list.add(new StockErrorProduct(pro.getId(),"商品可能已经下架或售完!"));
}
}
//检查积分是否足够支付此订单消耗的积分
//积分不足的错误提示
if(acc.getScore() < cartInfo.getTotalExchangeScore()){
result.error = "总共所需积分:" + cartInfo.getTotalExchangeScore() + ",可惜您仅有积分:" + acc.getScore();
}
if(list!=null && list.size()>0){
result.list = list;
}
cartInfo.totalCacl();//计算购物车中商品总金额
// logger.error("checkStockLastTime..."+JSON.toJSONString(result).toString());
return (JSON.toJSONString(result).toString());
}
/**
* 库存检查返回的错误对象
* @author huangf
*
*/
class StockErrorProductReturn{
String code;
String error;//错误消息,显示到提交按钮边上
List<StockErrorProduct> list;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public List<StockErrorProduct> getList() {
return list;
}
public void setList(List<StockErrorProduct> list) {
this.list = list;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
}
/**
* 库存检查错误消息对象
*/
class StockErrorProduct{
String id;//商品ID
String tips;//错误消息
public StockErrorProduct(){}
public StockErrorProduct(String id,String tips){
this.id = id;
this.tips = tips;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTips() {
return tips;
}
public void setTips(String tips) {
this.tips = tips;
}
}
/**
* 购物车页面,单个商品返回的信息对象
*/
class CartProductInfo {
String code;//返回代码
String msg;//返回消息
String total0;//小计金额
String amount;//总计金额
int totalExchangeScore;//兑换此商品所需总积分
int amountExchangeScore;//积分汇总
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getTotal0() {
return total0;
}
public void setTotal0(String total0) {
this.total0 = total0;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public int getTotalExchangeScore() {
return totalExchangeScore;
}
public void setTotalExchangeScore(int totalExchangeScore) {
this.totalExchangeScore = totalExchangeScore;
}
public int getAmountExchangeScore() {
return amountExchangeScore;
}
public void setAmountExchangeScore(int amountExchangeScore) {
this.amountExchangeScore = amountExchangeScore;
}
}
}
如果也想学习本系统,下面领取。回复:225ssm