Java项目:网上商城系统(java+SSM+jsp+mysql+maven)

  • Post author:
  • Post category:java



源码获取:博客首页 “资源” 里下载!

一、项目简述功能 
javaweb 网上商城系统,前台+后台管理,用户注册,登录,上哦展示,分组展示,搜索,收货地址管理,购物车管理,添加,购买,个人信息修改。订单查询等等,后台商品管理,分类管理,库存管理,订单管理,用户管理,信息修改等等.
二、项目运行 
环境配置: Jdk1.8 + Tomcats . 5 + mysql + Eclispe ( IntelliJ IDEA ,Eclispe , MyEclispe , sts 都支持)
项目技术: JSP + Spring + SpringMVC + MyBatis + html + cSS + Javascript + JQuery + Ajax + layui + maven 等等。


后台管理平台登录代码:

/**
 * 后台管理-主页
 */@ControllerpublicclassAdminHomeControllerextendsBaseController {
    @Resource(name = "adminService")private AdminService adminService;
    @Resource(name = "productOrderService")private ProductOrderService productOrderService;
    @Resource(name = "productService")private ProductService productService;
    @Resource(name = "userService")private UserService userService;

    /**
     * 转到后台管理-主页
     * @param session session对象
     * @param map 前台传入的Map
     * @return 响应数据
     * @throws ParseException 转换异常
     */@RequestMapping(value = "admin", method = RequestMethod.GET)public String goToPage(HttpSession session, Map<String, Object> map)throws ParseException {
        logger.info("获取管理员信息");
        ObjectadminId= checkAdmin(session);
        if (adminId == null) {
            return"redirect:/admin/login";
        }
        Adminadmin= adminService.get(null, Integer.parseInt(adminId.toString()));
        map.put("admin", admin);
        logger.info("获取统计信息");
        //产品总数IntegerproductTotal= productService.getTotal(null, newByte[]{0, 2});
        //用户总数IntegeruserTotal= userService.getTotal(null);
        //订单总数IntegerorderTotal= productOrderService.getTotal(null, newByte[]{3});
        logger.info("获取图表信息");
        map.put("jsonObject", getChartData(null,null,7));
        map.put("productTotal", productTotal);
        map.put("userTotal", userTotal);
        map.put("orderTotal", orderTotal);

        logger.info("转到后台管理-主页");
        return"admin/homePage";
    }

    /**
     * 转到后台管理-主页(ajax方式)
     * @param session session对象
     * @param map 前台传入的Map
     * @return 响应数据
     * @throws ParseException 转换异常
     */@RequestMapping(value = "admin/home", method = RequestMethod.GET)public String goToPageByAjax(HttpSession session, Map<String, Object> map)throws ParseException {
        logger.info("获取管理员信息");
        ObjectadminId= checkAdmin(session);
        if (adminId == null) {
            return"admin/include/loginMessage";
        }
        Adminadmin= adminService.get(null, Integer.parseInt(adminId.toString()));
        map.put("admin", admin);
        logger.info("获取统计信息");
        IntegerproductTotal= productService.getTotal(null, newByte[]{0, 2});
        IntegeruserTotal= userService.getTotal(null);
        IntegerorderTotal= productOrderService.getTotal(null, newByte[]{3});
        logger.info("获取图表信息");
        map.put("jsonObject", getChartData(null, null,7));
        logger.info("获取图表信息");
        map.put("jsonObject", getChartData(null,null,7));
        map.put("productTotal", productTotal);
        map.put("userTotal", userTotal);
        map.put("orderTotal", orderTotal);
        logger.info("转到后台管理-主页-ajax方式");
        return"admin/homeManagePage";
    }

    /**
     * 按日期查询图表数据(ajax方式)
     * @param beginDate 开始日期
     * @param endDate 结束日期
     * @return 响应数据
     * @throws ParseException 转换异常
     */@ResponseBody@RequestMapping(value = "admin/home/charts", method = RequestMethod.GET, produces = "application/json;charset=utf-8")public String getChartDataByDate(@RequestParam(required = false) String beginDate, @RequestParam(required = false) String endDate)throws ParseException {
        if (beginDate != null && endDate != null) {
            //转换日期格式SimpleDateFormatsimpleDateFormat=newSimpleDateFormat("yyyy-MM-dd");
            return getChartData(simpleDateFormat.parse(beginDate), simpleDateFormat.parse(endDate),7).toJSONString();
        } else {
            return getChartData(null, null,7).toJSONString();
        }
    }

    /**
     * 按日期获取图表数据
     * @param beginDate 开始日期
     * @param endDate 结束日期
     * @param days 天数
     * @return 图表数据的JSON对象
     * @throws ParseException 转换异常
     */private JSONObject getChartData(Date beginDate,Date endDate,int days)throws ParseException {
        JSONObjectjsonObject=newJSONObject();
        SimpleDateFormattime=newSimpleDateFormat("yyyy-MM-dd", Locale.UK);
        SimpleDateFormattime2=newSimpleDateFormat("MM/dd", Locale.UK);
        SimpleDateFormattimeSpecial=newSimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.UK);
        //如果没有指定开始和结束日期if (beginDate == null || endDate == null) {
            //指定一周前的日期为开始日期Calendarcal= Calendar.getInstance();
            cal.add(Calendar.DATE, 1-days);
            beginDate = time.parse(time.format(cal.getTime()));
            //指定当前日期为结束日期
            cal = Calendar.getInstance();
            endDate = cal.getTime();
        } else {
            beginDate = time.parse(time.format(beginDate));
            endDate = timeSpecial.parse(time.format(endDate) + " 23:59:59");
        }
        logger.info("根据订单状态分类");
        //未付款订单数统计数组int[] orderUnpaidArray = newint[7];
        //未发货订单数统计叔祖int[] orderNotShippedArray = newint[7];
        //未确认订单数统计数组int[] orderUnconfirmedArray = newint[7];
        //交易成功订单数统计数组int[] orderSuccessArray = newint[7];
        //总交易订单数统计数组int[] orderTotalArray = newint[7];
        logger.info("从数据库中获取统计的订单集合数据");
        List<OrderGroup> orderGroupList = productOrderService.getTotalByDate(beginDate, endDate);
        //初始化日期数组JSONArraydateStr=newJSONArray(days);
        //按指定的天数进行循环for (inti=0; i < days; i++) {
            //格式化日期串(MM/dd)并放入日期数组中Calendarcal= Calendar.getInstance();
            cal.setTime(beginDate);
            cal.add(Calendar.DATE, i);
            StringformatDate= time2.format(cal.getTime());
            dateStr.add(formatDate);
            //该天的订单总数intorderCount=0;
            //循环订单集合数据的结果集for(intj=0; j < orderGroupList.size(); j++){
                OrderGrouporderGroup= orderGroupList.get(j);
                //如果该订单日期与当前日期一致if(orderGroup.getProductOrder_pay_date().equals(formatDate)){
                    //从结果集中移除数据
                    orderGroupList.remove(j);
                    //根据订单状态将统计结果存入对应的订单状态数组中switch (orderGroup.getProductOrder_status()) {
                        case0:
                            //未付款订单
                            orderUnpaidArray[i] = orderGroup.getProductOrder_count();
                            break;
                        case1:
                            //未发货订单
                            orderNotShippedArray[i] = orderGroup.getProductOrder_count();
                            break;
                        case2:
                            //未确认订单
                            orderUnconfirmedArray[i] = orderGroup.getProductOrder_count();
                            break;
                        case3:
                            //交易成功订单
                            orderSuccessArray[i] = orderGroup.getProductOrder_count();
                            break;
                    }
                    //累加当前日期的订单总数
                    orderCount += orderGroup.getProductOrder_count();
                }
            }
            //将统计的订单总数存入总交易订单数统计数组
            orderTotalArray[i] = orderCount;
        }
        logger.info("返回结果集map");
        jsonObject.put("orderTotalArray", orderTotalArray);
        jsonObject.put("orderUnpaidArray", orderUnpaidArray);
        jsonObject.put("orderNotShippedArray", orderNotShippedArray);
        jsonObject.put("orderUnconfirmedArray", orderUnconfirmedArray);
        jsonObject.put("orderSuccessArray", orderSuccessArray);
        jsonObject.put("dateStr",dateStr);
        return jsonObject;
    }
}

用户相关接口:

/**
 * 用户相关接口
 */@Controller@RequestMapping("/index")publicclassUserController{
	
	@Resource
	private UserService userService;
	@Resource
	private OrderService orderService;
	@Resource
	private GoodService goodService;
	@Resource
	private TypeService typeService;
	@Resource
	private ShopcartService shopcartService;
	@Resource
	private SkuService skuService;

	
	/**
	 * 用户注册
	 * @return
	 */
	@GetMapping("/register")
	public String reg(Model model) {
		model.addAttribute("flag", -1); // 注册页面
		return"/index/register.jsp";
	}
	
	/**
	 * 用户注册
	 * @return
	 */
	@PostMapping("/register")
	public String register(Users user, Model model){
		if (user.getUsername().isEmpty()) {
			model.addAttribute("msg", "用户名不能为空!");
			return"/index/register.jsp";
		}elseif (userService.isExist(user.getUsername())) {
			model.addAttribute("msg", "用户名已存在!");
			return"/index/register.jsp";
		}else {
			Stringpassword= user.getPassword();
			userService.add(user);
			user.setPassword(password);
			return"/index/index"; // 注册成功后转去登录
		}
	}
	
	/**
	 * 用户登录
	 * @return
	 */
	@GetMapping("/login")
	public String log() {
		return"/index/index";
	}
	
	/**
	 * 用户登录
	 * @return
	 */
	@PostMapping("/login")
	public String login(@RequestParam(required=false, defaultValue="0")int flag, Users user, HttpSession session, Model model) {
		model.addAttribute("typeList", typeService.getList());
		if(flag==-1) {
			flag = 6; // 登录页面
			return"/index/index";
		}
		if(userService.checkUser(user.getUsername(), user.getPassword())){
			UsersloginUser= userService.get(user.getUsername());
			session.setAttribute("user", loginUser);
			// 还原购物车数量
			session.setAttribute("total", shopcartService.getTotal(loginUser.getId()));
			return"redirect:index";
		} else {
			model.addAttribute("msg", "用户名或密码错误!");
			return"/index/index";
		}
	}

	/**
	 * 注销登录
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		session.removeAttribute("user");
		session.removeAttribute("order");
		return"/index/index";
	}
	
	/**
	 * 查看购物车
	 * @return
	 */
	@RequestMapping("/shopcart")
	public String shopcart(Model model, HttpSession session) {
		Usersuser= (Users) session.getAttribute("user");
		if (user == null) {
			model.addAttribute("msg", "请先登录!");
			return"/index/index";
		}
		model.addAttribute("typeList", typeService.getList());
		model.addAttribute("shopcartList", shopcartService.getList(user.getId()));
		model.addAttribute("totalPrice", shopcartService.getTotalPrice(user.getId()));
		return"/index/shopcart.jsp";
	}
	
	/**
	 * 购买
	 * @return
	 */
	@RequestMapping("/buy")
	public@ResponseBodyintbuy(Shopcart shopcart, HttpSession session, Model model){
		Usersuser= (Users) session.getAttribute("user");
		if (user == null) {
			return -111;
		}
		shopcart.setUserId(user.getId());
		shopcart.setGood(goodService.get(shopcart.getGoodId()));
		// 验证库存//		int stock = skuService.getStock(shopcart.getGoodId(), shopcart.getColorId(), shopcart.getSizeId());//		if(shopcart.getAmount() > stock) {//			model.addAttribute("msg", "商品 [ " + shopcart.getGood().getName() + " ] 库存不足! 当前库存只有: " + stock);//		}
		return orderService.save(Arrays.asList(shopcart), user);
	}
	
	/**
	 * 购买
	 * @return
	 */
	@RequestMapping("/cart")
	public@ResponseBodyintcart(Shopcart shopcart, HttpSession session, Model model){
		Usersuser= (Users) session.getAttribute("user");
		if (user == null) {
			return -111;
		}
		shopcart.setUserId(user.getId());
		shopcartService.save(shopcart);
		inttotal= shopcartService.getTotal(user.getId());
		session.setAttribute("total", total);
		return total;
	}
	
	/**
	 * 添加
	 */
	@RequestMapping("/add")
	public@ResponseBodybooleanadd(int skuid, HttpSession session){
		Usersuser= (Users) session.getAttribute("user");
		if (user == null) {
			returnfalse;
		}
		return shopcartService.add(skuid);
	}
	
	/**
	 * 减少
	 */
	@RequestMapping("/less")
	public@ResponseBodybooleanless(int skuid, HttpSession session){
		Usersuser= (Users) session.getAttribute("user");
		if (user == null) {
			returnfalse;
		}
		return shopcartService.less(skuid);
	}
	
	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	public@ResponseBodybooleandelete(int skuid, HttpSession session){
		Usersuser= (Users) session.getAttribute("user");
		if (user == null) {
			returnfalse;
		}
		shopcartService.delete(skuid);
		session.setAttribute("total", shopcartService.getTotal(user.getId()));
		returntrue;
	}
	
	/**
	 * 总金额
	 * @return
	 */
	@RequestMapping("/total")
	public@ResponseBodyinttotal(HttpSession session){
		Usersuser= (Users) session.getAttribute("user");
		if (user == null) {
			return -111;
		}
		return shopcartService.getTotalPrice(user.getId());
	}
	
	
	/**
	 * 提交订单
	 * @return
	 */
	@RequestMapping("/save")
	public String save(ServletRequest request, HttpSession session, Model model){
		Usersuser= (Users) session.getAttribute("user");
		if (user == null) {
			model.addAttribute("msg", "请先登录!");
			return"/index/index";
		}
		List<Shopcart> shopcartList = shopcartService.getList(user.getId());
		if(Objects.isNull(shopcartList) || shopcartList.isEmpty()) {
			model.addAttribute("msg", "购物车没有商品");
			return shopcart(model, session);
		}
		// 验证库存
		for(Shopcart cart : shopcartList) {
			intstock= skuService.getStock(cart.getGoodId(), cart.getColorId(), cart.getSizeId());
			if(cart.getAmount() > stock) {
				model.addAttribute("msg", "商品 [ " + cart.getGood().getName() + " ] 库存不足! 当前库存只有: " + stock);
				return shopcart(model, session);
			}
		}
		intorderid= orderService.save(shopcartList, user);
		if(orderid > 0) {
			// 清空购物车
			session.setAttribute("total", shopcartService.getTotal(user.getId()));
			// 跳转支付
			return"redirect:topay?orderid="+orderid;
		} 

		model.addAttribute("msg", "出了点问题");
		return shopcart(model, session);
	}
	
	/**
	 * 支付页面
	 * @return
	 */
	@RequestMapping("/topay")
	public String topay(int orderid, ServletRequest request, HttpSession session) {
		Usersuser= (Users) session.getAttribute("user");
		if (user == null) {
			request.setAttribute("msg", "请先登录!");
			return"/index/index";
		}
		request.setAttribute("typeList", typeService.getList());
		request.setAttribute("order", orderService.get(orderid));
		return"/index/pay.jsp";
	}
	
	/**
	 * 支付(模拟)
	 * @return
	 */
	@RequestMapping("/pay")
	public String pay(Orders order, ServletRequest request, HttpSession session) {
		Usersuser= (Users) session.getAttribute("user");
		if (user == null) {
			request.setAttribute("msg", "请先登录!");
			return"/index/index";
		}
		// 模拟支付
		orderService.pay(order);
		request.setAttribute("typeList", typeService.getList());
		request.setAttribute("order", orderService.get(order.getId()));
		request.setAttribute("msg", "支付成功! 即将跳转到订单列表");
		return"/index/pay.jsp";
	}
	
	/**
	 * 查看订单
	 * @return
	 */
	@RequestMapping("/order")
	public String order(HttpSession session, Model model){
		model.addAttribute("flag", 12);
		Usersuser= (Users) session.getAttribute("user");
		if (user == null) {
			model.addAttribute("msg", "请登录后查看订单!");
			return"/index/index";
		}
		model.addAttribute("typeList", typeService.getList());
		model.addAttribute("orderList", orderService.getListByUserid(user.getId()));
		return"/index/order.jsp";
	}
	
	
	/**
	 * 个人信息
	 * @return
	 */
	@RequestMapping("/my")
	public String my(HttpSession session, Model model){
		model.addAttribute("flag", 11);
		model.addAttribute("typeList", typeService.getList());
		Usersuser= (Users) session.getAttribute("user");
		if (user == null) {
			model.addAttribute("msg", "请先登录!");
			return"/index/index";
		}
		model.addAttribute("user", user);
		return"/index/my.jsp";
	}
	
	
	/**
	 * 修改信息
	 * @return
	 */
	@RequestMapping("/updateUser")
	public String updateUser(Users user, HttpSession session, Model model){
		model.addAttribute("flag", 11);
		model.addAttribute("typeList", typeService.getList());
		UsersuserLogin= (Users) session.getAttribute("user");
		if (userLogin == null) {
			model.addAttribute("msg", "请先登录!");
			return"/index/index";
		}
		// 修改资料
		Usersu= userService.get(userLogin.getId());
		u.setName(user.getName());
		u.setPhone(user.getPhone());
		u.setAddress(user.getAddress());
		userService.update(u);  // 更新数据库
		session.setAttribute("user", u); // 更新session
		model.addAttribute("msg", "信息修改成功!");
		return"/index/my.jsp";
	}
	
	
	/**
	 * 修改信息
	 * @return
	 */
	@RequestMapping("/updatePassword")
	public String updatePassword(Users user, HttpSession session, Model model){
		model.addAttribute("flag", 11);
		model.addAttribute("typeList", typeService.getList());
		UsersuserLogin= (Users) session.getAttribute("user");
		if (userLogin == null) {
			model.addAttribute("msg", "请先登录!");
			return"/index/index";
		}
		// 修改密码
		Usersu= userService.get(userLogin.getId());
		if(user.getPasswordNew()!=null && !user.getPasswordNew().trim().isEmpty()) {
			if (user.getPassword()!=null && !user.getPassword().trim().isEmpty() 
					&& SafeUtil.encode(user.getPassword()).equals(u.getPassword())) {
				if (user.getPasswordNew()!=null && !user.getPasswordNew().trim().isEmpty()) {
					u.setPassword(SafeUtil.encode(user.getPasswordNew()));
				}
				userService.update(u);  // 更新数据库
				session.setAttribute("user", u); // 更新session
				model.addAttribute("msg", "密码修改成功!");
				return"redirect:logout";
			}else {
				model.addAttribute("msg", "原密码错误!");
			}
		}
		return"/index/index";
	}
	
}

前台相关接口:

/**
 * 前台相关接口
 */@Controller@RequestMapping("/index")publicclassIndexController{
	
	privatestaticfinalintrows=8; // 默认每页数量

	@Autowired
	private TopService topService;
	@Autowired
	private GoodService goodService;
	@Autowired
	private TypeService typeService;
	@Autowired
	private SkuService skuService;
	

	/**
	 * 首页
	 * @return
	 */
	@RequestMapping("/index")
	public String index(HttpServletRequest request){
		request.setAttribute("flag", -1);
		List<Types> typeList = typeService.getList();
		request.setAttribute("typeList", typeList);
		List<Map<String, Object>> dataList = newArrayList<>();
		for(Types type : typeList) {
			Map<String, Object> map = newHashMap<>();
			map.put("type", type);
			map.put("goodList", goodService.getListByType(type.getId(), 1, 8)); // 取前8个
			dataList.add(map);
		}
		request.setAttribute("dataList", dataList);
		return"/index/index.jsp";
	}
	
	/**
	 * 推荐列表
	 * @return
	 */
	@RequestMapping("/top")
	public String tops(int typeid, @RequestParam(required=false, defaultValue="1")int page, HttpServletRequest request) {
		request.setAttribute("flag", typeid==2 ? 7 : 8);
		request.setAttribute("typeList", typeService.getList());
		request.setAttribute("goodList", goodService.getList(typeid, page, rows));
		request.setAttribute("pageHtml", PageUtil.getPageHtml(request, goodService.getTotal(typeid), page, rows));
		return"/index/goods.jsp";
	}
	
	/**
	 * 商品列表
	 * @return
	 */
	@RequestMapping("/goods")
	public String goods(int typeid, @RequestParam(required=false, defaultValue="1")int page, HttpServletRequest request){
		request.setAttribute("flag", typeid);
		request.setAttribute("typeList", typeService.getList());
		request.setAttribute("topList", topService.getList(Tops.TYPE_SUPPER, 1, 4));
		if (typeid > 0) {
			request.setAttribute("type", typeService.get(typeid));
		}
		request.setAttribute("goodList", goodService.getListByType(typeid, page, rows));
		request.setAttribute("pageHtml", PageUtil.getPageHtml(request, goodService.getTotalByType(typeid), page, rows));
		return"/index/goods.jsp";
	}
	
	/**
	 * 商品详情
	 * @return
	 */
	@RequestMapping("/detail")
	public String detail(int goodid, HttpServletRequest request){
		request.setAttribute("typeList", typeService.getList());
		request.setAttribute("topList", topService.getList(Tops.TYPE_SUPPER, 1, 4));
		Goodsgood= goodService.get(goodid);
		request.setAttribute("good", good);
		request.setAttribute("type", typeService.get(good.getTypeId()));
		request.setAttribute("colorList", skuService.getColorList(goodid));
		request.setAttribute("sizeList", skuService.getSizeList(goodid));
		return"/index/detail.jsp";
	}
	
	/**
	 * 搜索
	 * @return
	 */
	@RequestMapping("/search")
	public String search(String name, @RequestParam(required=false, defaultValue="1")int page, HttpServletRequest request) {
		if (Objects.nonNull(name) && !name.trim().isEmpty()) {
			request.setAttribute("goodList", goodService.getListByName(name, page, rows));
			request.setAttribute("pageHtml", PageUtil.getPageHtml(request, goodService.getTotalByName(name), page, rows));
		}
		request.setAttribute("typeList", typeService.getList());
		return"/index/goods.jsp";
	}
	
	/**
	 * 查询库存
	 * @param goodid
	 * @param colorid
	 * @param sizeid
	 * @return
	 */
	@GetMapping("/stock")
	public@ResponseBodyintstock(int goodid, int colorid, int sizeid) {
		return skuService.getStock(goodid, colorid, sizeid);
	}

}


源码获取:博客首页 “资源” 里下载!



版权声明:本文为2301_76223934原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。