基于javaweb+mysql的springboot水果生鲜商城系统(java+springboot+maven+mybatis+vue+mysql+redis)
运行环境
Java≥8、MySQL≥5.7、Node.js≥10
开发工具
后端:eclipse/idea/myeclipse/sts等均可配置运行
前端:WebStorm/VSCode/HBuilderX等均可
适用
课程设计,大作业,毕业设计,项目练习,学习演示等
功能说明
基于javaweb+mysql的SpringBoot水果生鲜商城系统(java+springboot+maven+mybatis+vue+mysql+redis)
一、项目简述 本系统功能包括: 商品的分类展示,用户的注册登录,购物车,订单结算,购物车加减,后台商品管理,分类管理,订单管理等等功能。
二、项目运行 环境配置:
Jdk1.8 + Tomcat8.5 + Mysql + HBuilderX(Webstorm也行)+ Eclispe(IntelliJ IDEA,Eclispe,MyEclispe,Sts都支持)。
项目技术:
Springboot + Maven + mybatis+ Vue 等等组成,B/S模式 + Maven管理等等。
public ApiRestResponse updateState(@RequestParam Integer id, @RequestParam Integer state) {
productService.updateState(id,state);
return ApiRestResponse.success();
}
@ApiOperation("后台删除商品")
@PostMapping("/product/delete")
public ApiRestResponse deleteProduct(@RequestParam Integer id) {
productService.delete(id);
return ApiRestResponse.success();
}
@ApiOperation("后台批量上下架")
@PostMapping("/product/batchUpdateSellStatus")
public ApiRestResponse batchUpdateSellStatus(@RequestParam Integer[] ids,@RequestParam Integer sellStatus) {
productService.batchUpdateSellStatus(ids, sellStatus);
return ApiRestResponse.success();
}
@ApiOperation("后台批量上下架")
@PostMapping("/product/updateImgGuid")
public ApiRestResponse batchUpdateSellStatus(@RequestParam String guid,@RequestParam Integer id) {
// productService.batchUpdateSellStatus(ids, sellStatus);
productService.updateImg(id,guid);
return ApiRestResponse.success();
}
@ApiOperation("架")
@PostMapping("/product/updateImgGuid1")
public ApiRestResponse updateImgGuid(@RequestParam String guid, @RequestParam int id) {
return ApiRestResponse.success();
}
@ApiOperation("后台商品列表")
@PostMapping("/product/list")
public ApiRestResponse list(@RequestParam Integer pageNum, @RequestParam Integer pageSize) {
PageInfo pageInfo = productService.listForAdmin(pageNum, pageSize);
return ApiRestResponse.success(pageInfo);
}
}
}else {
log.error("订单" + orderNo + "支付二维码文件:" + Constant.FILE_UPLOAD_DIR + orderNo + ".png not create");
}
}
@Override
public PageInfo listForAdmin(Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<Order> orderList = orderMapper.selectAll();
List<OrderVO> orderVOList = this.orderListToOrderVOList(orderList);
PageInfo pageInfo = new PageInfo<>(orderList);
pageInfo.setList(orderVOList);
return pageInfo;
}
@Override
public void delivered(String orderNo) {
Order oldOrder = this.isOrderNotNull(orderNo);
if (!oldOrder.getOrderStatus().equals(Constant.OrderStatusEnum.PAID.getCode())) {
throw new GobMallException(GobMallExceptionEnum.WRONG_ORDER_STATUS);
}
Order newOrder = new Order();
newOrder.setId(oldOrder.getId());
newOrder.setOrderStatus(Constant.OrderStatusEnum.DELIVERED.getCode());
newOrder.setDeliveryTime(new Date());
orderMapper.updateByPrimaryKeySelective(newOrder);
}
@Override
public void finish(String orderNo) {
Order oldOrder = this.isOrderNotNull(orderNo);
if (!oldOrder.getOrderStatus().equals(Constant.OrderStatusEnum.DELIVERED.getCode())) {
throw new GobMallException(GobMallExceptionEnum.WRONG_ORDER_STATUS);
}
Order newOrder = new Order();
newOrder.setId(oldOrder.getId());
newOrder.setOrderStatus(Constant.OrderStatusEnum.FINISHED.getCode());
newOrder.setEndTime(new Date());
orderMapper.updateByPrimaryKeySelective(newOrder);
}
}
}
/**
* 全局异常处理
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理系统异常(非业务之内异常)
*/
@ExceptionHandler(Exception.class)
public ApiRestResponse<Object> handlerException(Exception e) {
log.error("Default Exception : ", e);
return ApiRestResponse.error(GobMallExceptionEnum.SYSTEM_ERROR);
}
/**
* 业务异常
*/
@ExceptionHandler(GobMallException.class)
public ApiRestResponse<Object> handlerGobMallException(GobMallException e) {
log.error("GobMallException Exception : ", e);
return ApiRestResponse.error(e.getCode(), e.getMessage());
}
/**
* 接口请求时参数校验未通过异常处理
" \"status\": 10009,\n" +
"\"msg\": \"没有权限\",\n" +
"\"data\": null\n" +
"}");
out.flush();
out.close();
}
}
}
@Override
public void destroy() {
}
}
public class CorsFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) {
// TODO Auto-generated method stub
}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (request instanceof HttpServletRequest) {
String [] allowDomain= {"http://localhost:81","http://localhost:8081","http://192.168.43.69","http://192.168.43.69:8080"};
Set<String> allowedOrigins= new HashSet<String>(Arrays.asList(allowDomain));
String originHeader=((HttpServletRequest) request).getHeader("Origin");
if (!allowedOrigins.contains(originHeader)) {
originHeader = "http://localhost";
}
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
httpServletResponse.setHeader("Access-Control-Allow-Origin", originHeader);
httpServletResponse.setHeader("Access-Control-Allow-Methods",
"POST, GET, PUT, OPTIONS, DELETE");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
httpServletResponse.setHeader("Access-Control-Allow-Headers",
public class UserController {
@Autowired
UserService userService;
/**
* 注册
*/
@ApiOperation("注册")
@PostMapping("register")
public ApiRestResponse<Object> register(@RequestParam("username") String username, @RequestParam("password") String password) throws GobMallException {
if (StringUtils.isEmpty(username)) {
return ApiRestResponse.error(GobMallExceptionEnum.NEED_USER_NAME);
}
if (StringUtils.isEmpty(password)) {
return ApiRestResponse.error(GobMallExceptionEnum.NEED_PASSWORD);
}
//密码长度不能少于八位
if (password.length() < 8) {
return ApiRestResponse.error(GobMallExceptionEnum.PASSWORD_TOO_SHORT);
}
userService.register(username, password);
return ApiRestResponse.success();
}
/**
* 登录
*/
@ApiOperation("登录")
@PostMapping("login")
public ApiRestResponse<User> login(@RequestParam("username") String username, @RequestParam("password") String password, HttpSession session) throws GobMallException {
if (StringUtils.isEmpty(username)) {
return ApiRestResponse.error(GobMallExceptionEnum.NEED_USER_NAME);
}
if (StringUtils.isEmpty(password)) {
return ApiRestResponse.error(GobMallExceptionEnum.NEED_PASSWORD);
}
//保存用户信息时,不保存密码
User user = userService.login(username, password);
user.setPassword(null);
session.setAttribute(Constant.GOB_MALL_USER, user);
return ApiRestResponse.success(user);
}
/**
* 更新个性签名
*/
@ApiOperation("更新个性签名")
List<Product> recommend = productService.recommend(size);
return ApiRestResponse.success(recommend);
}
}
/**
* 管理员校验过滤器 : 对需要管理员权限的接口进行过滤,过滤拦截没有权限的请求,并返回错误信息
*/
public class UserFilter implements Filter {
public static ThreadLocal<User> currentUser = new ThreadLocal<>();
@Autowired
private UserService userService;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
User currentUser = UserHandler.checkUserLogin(request, response);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
if (currentUser != null) {
UserFilter.currentUser.set(currentUser);
chain.doFilter(request,response);
}
}
}
}
@Override
public String qrCode(String orderNo) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
String address = ip + ":" + request.getLocalPort();
String payUrl = "http://" + address + "/pay?orderNo=" + orderNo;
try {
QRCodeGenerator.generateQRCodeImage(payUrl, 350, 350, Constant.FILE_UPLOAD_DIR + orderNo + ".png");
log.info("订单" + orderNo + "支付二维码文件:" + Constant.FILE_UPLOAD_DIR + orderNo + ".png is create");
} catch (WriterException | IOException e) {
log.error("订单" + orderNo + "支付二维码文件:" + Constant.FILE_UPLOAD_DIR + orderNo + ".png is not create");
e.printStackTrace();
}
return "http://" + address + "/images/" + orderNo + ".png";
}
@Override
public void pay(String orderNo) {
Order oldOrder = this.isOrderNotNull(orderNo);
if (!oldOrder.getOrderStatus().equals(Constant.OrderStatusEnum.NOT_PAID.getCode())) {
throw new GobMallException(GobMallExceptionEnum.WRONG_ORDER_STATUS);
}
Order newOrder = new Order();
newOrder.setId(oldOrder.getId());
newOrder.setOrderStatus(Constant.OrderStatusEnum.PAID.getCode());
newOrder.setPayTime(new Date());
orderMapper.updateByPrimaryKeySelective(newOrder);
File file = new File(Constant.FILE_UPLOAD_DIR + orderNo + ".png");
if(true || file.delete()){
log.info("订单" + orderNo + "支付二维码文件:" + Constant.FILE_UPLOAD_DIR + orderNo + ".png is delete");
}else {
log.error("订单" + orderNo + "支付二维码文件:" + Constant.FILE_UPLOAD_DIR + orderNo + ".png not create");
}
}
@Override
public PageInfo listForAdmin(Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<Order> orderList = orderMapper.selectAll();
List<OrderVO> orderVOList = this.orderListToOrderVOList(orderList);
PageInfo pageInfo = new PageInfo<>(orderList);
pageInfo.setList(orderVOList);
return pageInfo;
}
@Override
private final ProductService productService;
public ProductController(ProductService productService) {
this.productService = productService;
}
@ApiOperation("商品详情")
@GetMapping("/detail")
public ApiRestResponse detail(@RequestParam Integer id) {
Product product = productService.detail(id);
return ApiRestResponse.success(product);
}
@ApiOperation("前台列表")
@GetMapping("/list")
public ApiRestResponse list(ProductListReq productListReq) {
PageInfo pageInfo = productService.list(productListReq);
return ApiRestResponse.success(pageInfo);
}
@ApiOperation("推荐")
@GetMapping("/recommend")
public ApiRestResponse recommend(Integer size) {
List<Product> recommend = productService.recommend(size);
return ApiRestResponse.success(recommend);
}
}
/**
* 管理员校验过滤器 : 对需要管理员权限的接口进行过滤,过滤拦截没有权限的请求,并返回错误信息
*/
public class UserFilter implements Filter {
if (StringUtils.isEmpty(password)) {
return ApiRestResponse.error(GobMallExceptionEnum.NEED_PASSWORD);
}
//保存用户信息时,不保存密码
User user = userService.login(username, password);
if (userService.checkAdminRole(user)) {
user.setPassword(null);
session.setAttribute(Constant.GOB_MALL_USER, user);
return ApiRestResponse.success(user);
}
return ApiRestResponse.error(GobMallExceptionEnum.NEED_ADMIN);
}
}
/**
* 购物车控制器
*/
@RestController
@RequestMapping("/cart")
public class CartController {
private final CartService cartService;
public CartController(CartService cartService) {
this.cartService = cartService;
}
@ApiOperation("购物车列表")
@GetMapping("/list")
public ApiRestResponse list() {
List<CartVO> list = cartService.list(UserFilter.currentUser.get().getId());
return ApiRestResponse.success(list);
}
/**
* 管理员校验过滤器 : 对需要管理员权限的接口进行过滤,过滤拦截没有权限的请求,并返回错误信息
*/
public class UserFilter implements Filter {
public static ThreadLocal<User> currentUser = new ThreadLocal<>();
@Autowired
private UserService userService;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
User currentUser = UserHandler.checkUserLogin(request, response);
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
if (currentUser != null) {
UserFilter.currentUser.set(currentUser);
chain.doFilter(request,response);
}
}
@Override
public void destroy() {
}
}
}
}
/**
* api请求日志处理切面
*/
@Aspect
@Component
public class WebLogAspect {
private final Logger log = LoggerFactory.getLogger(WebLogAspect .class);
@Pointcut("execution(public * cn.goodboyding.mall.controller.*.*(..))")
public void webLog() {
}
/**
* 请求前收集请求参数并记录
*/
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
//收到请求信息,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
log.info("URL : " + request.getRequestURL().toString());
log.info("HTTP_METHOD : " + request.getMethod());
log.info("IP : " + request.getRemoteAddr());
log.info("ClASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
orderService.finish(orderNo);
return ApiRestResponse.success();
}
}
/**
* 全局异常处理
*/
@RestControllerAdvice
public class GlobalExceptionHandler {
private final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 处理系统异常(非业务之内异常)
*/
@ExceptionHandler(Exception.class)
public ApiRestResponse<Object> handlerException(Exception e) {
log.error("Default Exception : ", e);
return ApiRestResponse.error(GobMallExceptionEnum.SYSTEM_ERROR);
}
/**
* 业务异常
*/
@ExceptionHandler(GobMallException.class)
public ApiRestResponse<Object> handlerGobMallException(GobMallException e) {
log.error("GobMallException Exception : ", e);
return ApiRestResponse.error(e.getCode(), e.getMessage());
}
/**
* 接口请求时参数校验未通过异常处理
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ApiRestResponse<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
log.error("MethodArgumentNotValidException : ", e);
return handleBindingResult(e.getBindingResult());
}
log.info("订单" + orderNo + "支付二维码文件:" + Constant.FILE_UPLOAD_DIR + orderNo + ".png is delete");
}else {
log.error("订单" + orderNo + "支付二维码文件:" + Constant.FILE_UPLOAD_DIR + orderNo + ".png not create");
}
}
@Override
public PageInfo listForAdmin(Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<Order> orderList = orderMapper.selectAll();
List<OrderVO> orderVOList = this.orderListToOrderVOList(orderList);
PageInfo pageInfo = new PageInfo<>(orderList);
pageInfo.setList(orderVOList);
return pageInfo;
}
@Override
public void delivered(String orderNo) {
Order oldOrder = this.isOrderNotNull(orderNo);
if (!oldOrder.getOrderStatus().equals(Constant.OrderStatusEnum.PAID.getCode())) {
throw new GobMallException(GobMallExceptionEnum.WRONG_ORDER_STATUS);
}
Order newOrder = new Order();
newOrder.setId(oldOrder.getId());
newOrder.setOrderStatus(Constant.OrderStatusEnum.DELIVERED.getCode());
newOrder.setDeliveryTime(new Date());
orderMapper.updateByPrimaryKeySelective(newOrder);
}
@Override
public void finish(String orderNo) {
Order oldOrder = this.isOrderNotNull(orderNo);
if (!oldOrder.getOrderStatus().equals(Constant.OrderStatusEnum.DELIVERED.getCode())) {
throw new GobMallException(GobMallExceptionEnum.WRONG_ORDER_STATUS);
}
Order newOrder = new Order();
newOrder.setId(oldOrder.getId());
newOrder.setOrderStatus(Constant.OrderStatusEnum.FINISHED.getCode());
newOrder.setEndTime(new Date());
orderMapper.updateByPrimaryKeySelective(newOrder);
}
}
}
}
}
/**
* 将cartVO转换未OrderItem
*/
private List<OrderItem> cartVOListToOrderItemList(List<CartVO> cartVOList) {
List<OrderItem> orderItemList = new ArrayList<>();
for (CartVO cartVO : cartVOList) {
OrderItem orderItem = new OrderItem();
//记录商品快照
orderItem.setProductId(cartVO.getProductId());
orderItem.setProductName(cartVO.getProductName());
orderItem.setProductImg(cartVO.getProductImage());
orderItem.setUnitPrice(cartVO.getPrice());
orderItem.setQuantity(cartVO.getQuantity());
orderItem.setTotalPrice(cartVO.getTotalPrice());
orderItemList.add(orderItem);
}
return orderItemList;
}
/**
* 清空购物车中已下单的商品(被选中的商品)
*/
private void cleanCart(List<CartVO> cartVOList) {
for (CartVO cartVO : cartVOList) {
cartMapper.deleteByPrimaryKey(cartVO.getId());
}
}
/**
* 计算订单总价
*/
private Integer totalPrice(List<OrderItem> orderItemList) {
Integer totalPrice = 0;
for (OrderItem orderItem : orderItemList) {
totalPrice += orderItem.getTotalPrice();
}
return totalPrice;
}
/**
* Order转OrderVO
*/
private OrderVO orderToOrderVO(Order order) {
OrderVO orderVO = new OrderVO();
BeanUtils.copyProperties(order, orderVO);
List<OrderItemVO> orderItemVOList = new ArrayList<>();
@ApiOperation("后台删除目录")
@PostMapping("/admin/category/delete")
public ApiRestResponse<Object> deleteCategory(@RequestParam("id") Integer id) {
categoryService.delete(id);
return ApiRestResponse.success();
}
@ApiOperation("目录列表分页查询(管理员)")
@GetMapping("admin/category/list")
public ApiRestResponse<Object> listCategoryAdmin(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {
PageInfo<Category> pageInfo = categoryService.listForAdmin(pageNum, pageSize);
return ApiRestResponse.success(pageInfo);
}
@ApiOperation("目录列表分页查询")
@GetMapping("category/list")
public ApiRestResponse<Object> listCategoryCustomer() {
List<CategoryVO> categoryVos = categoryService.listCategoryForCustomer(0);
return ApiRestResponse.success(categoryVos);
}
@GetMapping("/admin/category/listByType")
public ApiRestResponse<Object> listByType(@RequestParam Integer type) {
List<Category> categoryList = categoryService.listByType(type);
return ApiRestResponse.success(categoryList);
}
}
@RestController
public class OrderController {
private final OrderService orderService;
@ApiOperation("后台删除目录")
@PostMapping("/admin/category/delete")
public ApiRestResponse<Object> deleteCategory(@RequestParam("id") Integer id) {
categoryService.delete(id);
return ApiRestResponse.success();
}
@ApiOperation("目录列表分页查询(管理员)")
@GetMapping("admin/category/list")
public ApiRestResponse<Object> listCategoryAdmin(@RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {
PageInfo<Category> pageInfo = categoryService.listForAdmin(pageNum, pageSize);
return ApiRestResponse.success(pageInfo);
}
@ApiOperation("目录列表分页查询")
@GetMapping("category/list")
public ApiRestResponse<Object> listCategoryCustomer() {
List<CategoryVO> categoryVos = categoryService.listCategoryForCustomer(0);
return ApiRestResponse.success(categoryVos);
}
@GetMapping("/admin/category/listByType")
public ApiRestResponse<Object> listByType(@RequestParam Integer type) {
List<Category> categoryList = categoryService.listByType(type);
return ApiRestResponse.success(categoryList);
}
}
@RestController
/**
* 订单service实现类
*/
@Service
public class OrderServiceImpl implements OrderService {