基于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管理等等。
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);
*/
@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());
}
private ApiRestResponse<Object> handleBindingResult(BindingResult result) {
//把异常处理为对外保留的提示
List<String> list = new ArrayList<>();
if (result.hasErrors()) {
List<ObjectError> allErrors = result.getAllErrors();
for (ObjectError error : allErrors) {
String message = error.getDefaultMessage();
list.add(message);
}
}
if (list.size() == 0) {
return ApiRestResponse.error(GobMallExceptionEnum.REQUEST_PARAM_ERROR);
}
return ApiRestResponse.error(GobMallExceptionEnum.REQUEST_PARAM_ERROR.getCode(), list.toString());
}
}
log.info("ClASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
log.info("ARGS : " + Arrays.toString(joinPoint.getArgs()));
}
/**
* 请求后收集响应结果并记录
*/
@AfterReturning(returning = "res",pointcut = "webLog()")
public void doAfterReturning(Object res) throws JsonProcessingException {
//处理完请求返回内容
log.info("RESPONSE : " + new ObjectMapper().writeValueAsString(res));
}
}
/**
* 管理员校验过滤器 : 对需要管理员权限的接口进行过滤,过滤拦截没有权限的请求,并返回错误信息
*/
public class AdminFilter implements Filter {
@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 {
/**
* 订单service实现类
*/
@Service
public class OrderServiceImpl implements OrderService {
private final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);
private final CartService cartService;
private final ProductMapper productMapper;
private final CartMapper cartMapper;
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
@Value("${file.upload.ip}")
private String ip;
public OrderServiceImpl(CartService cartService, ProductMapper productMapper, CartMapper cartMapper, OrderMapper orderMapper, OrderItemMapper orderItemMapper) {
this.cartService = cartService;
this.productMapper = productMapper;
this.cartMapper = cartMapper;
this.orderMapper = orderMapper;
this.orderItemMapper = orderItemMapper;
}
/**
* 判断商品状态是否可售且库存足够
*/
private void validSaleStatusAndStock(List<CartVO> cartVOList) {
for (CartVO cartVO : cartVOList) {
Product product = productMapper.selectByPrimaryKey(cartVO.getProductId());
if (product == null || product.getStatus().equals(Constant.SaleStatus.NOT_SALE)) {
throw new GobMallException(GobMallExceptionEnum.NOT_SALE);
}
if (count < 0) {
throw new GobMallException(GobMallExceptionEnum.REQUEST_PARAM_ERROR);
}
List<CartVO> cartVOList = cartService.add(UserFilter.currentUser.get().getId(), productId, count);
return ApiRestResponse.success(cartVOList);
}
@ApiOperation("更新购物车信息")
@PostMapping("/update")
public ApiRestResponse update(@RequestParam Integer productId, @RequestParam Integer count) {
if (count < 0) {
throw new GobMallException(GobMallExceptionEnum.REQUEST_PARAM_ERROR);
}
List<CartVO> cartVOS = cartService.update(UserFilter.currentUser.get().getId(), productId, count);
return ApiRestResponse.success(cartVOS);
}
@ApiOperation("删除购物车中商品")
@PostMapping("/delete")
public ApiRestResponse delete(@RequestParam Integer productId) {
List<CartVO> cartVOS = cartService.delete(UserFilter.currentUser.get().getId(), productId);
return ApiRestResponse.success(cartVOS);
}
@ApiOperation("选中商品或取消选中")
@PostMapping("/select")
public ApiRestResponse select(@RequestParam Integer productId, @RequestParam Integer selected) {
List<CartVO> cartVOList = cartService.selectOrNot(UserFilter.currentUser.get().getId(), productId, selected);
return ApiRestResponse.success(cartVOList);
}
@ApiOperation("商品全选或取消全选")
@PostMapping("selectAll")
public ApiRestResponse selectAll(@RequestParam Integer selected) {
List<CartVO> cartVOList = cartService.selectAll(UserFilter.currentUser.get().getId(), selected);
return ApiRestResponse.success(cartVOList);
}
}
orderMapper.insertSelective(order);
//循环保存每个商品到order_item表
for (OrderItem orderItem : orderItemList) {
orderItem.setOrderNo(order.getOrderNo());
orderItemMapper.insertSelective(orderItem);
}
//返回结构
return orderCode;
}
@Override
public OrderVO detail(String orderNo) {
Order order = validOrder(orderNo);
return this.orderToOrderVO(order);
}
@Override
public PageInfo listForCustomer(Integer pageNum, Integer pageSize) {
Integer userId = UserFilter.currentUser.get().getId();
PageHelper.startPage(pageNum, pageSize);
List<Order> orderList = orderMapper.selectForCustomer(userId);
List<OrderVO> orderVOList = this.orderListToOrderVOList(orderList);
PageInfo pageInfo = new PageInfo<>(orderList);
pageInfo.setList(orderVOList);
return pageInfo;
}
@Override
public void cancel(String orderNo) {
Order order = validOrder(orderNo);
if (order.getOrderStatus().equals(Constant.OrderStatusEnum.NOT_PAID.getCode())) {
order.setOrderStatus(Constant.OrderStatusEnum.CANCELED.getCode());
order.setEndTime(new Date());
orderMapper.updateByPrimaryKeySelective(order);
} else {
throw new GobMallException(GobMallExceptionEnum.WRONG_ORDER_STATUS);
}
}
@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();
}
/**
* 购物车控制器
*/
@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);
}
@ApiOperation("购物车中选中商品")
@GetMapping("/list/selected")
public ApiRestResponse listOfSelected() {
List<CartVO> cartVOList = cartService.listOfSelected(UserFilter.currentUser.get().getId());
return ApiRestResponse.success(cartVOList);
}
@ApiOperation("添加商品到购物车")
@PostMapping("/add")
public ApiRestResponse add(@RequestParam Integer productId, @RequestParam Integer count) {
if (count < 0) {
throw new GobMallException(GobMallExceptionEnum.REQUEST_PARAM_ERROR);
}
List<CartVO> cartVOList = cartService.add(UserFilter.currentUser.get().getId(), productId, count);
return ApiRestResponse.success(cartVOList);
}
@ApiOperation("更新购物车信息")
@PostMapping("/update")
public ApiRestResponse update(@RequestParam Integer productId, @RequestParam Integer count) {
if (count < 0) {
throw new GobMallException(GobMallExceptionEnum.REQUEST_PARAM_ERROR);
}
List<CartVO> cartVOS = cartService.update(UserFilter.currentUser.get().getId(), productId, count);
return ApiRestResponse.success(cartVOS);
}
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) {
boolean adminRole = userService.checkAdminRole(currentUser);
if (adminRole) {
chain.doFilter(request,response);
} else {
PrintWriter out = new HttpServletResponseWrapper((HttpServletResponse) response).getWriter();
out.write("{\n" +
" \"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
}
URI effectiveURI;
try {
effectiveURI = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(), uri.getPort(), null, null, null);
} catch (URISyntaxException e) {
effectiveURI = null;
}
return effectiveURI;
}
@ApiOperation("后台更新商品")
@PostMapping("/product/update")
public ApiRestResponse updateProduct(@RequestBody @Valid UpdateProductReq updateProductReq) {
productService.update(updateProductReq);
return ApiRestResponse.success();
}
@ApiOperation("更新商品")
@PostMapping("/product/updateState")
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);
*/
private void validSaleStatusAndStock(List<CartVO> cartVOList) {
for (CartVO cartVO : cartVOList) {
Product product = productMapper.selectByPrimaryKey(cartVO.getProductId());
if (product == null || product.getStatus().equals(Constant.SaleStatus.NOT_SALE)) {
throw new GobMallException(GobMallExceptionEnum.NOT_SALE);
}
if (cartVO.getQuantity() > product.getStock()) {
throw new GobMallException(GobMallExceptionEnum.NOT_ENOUGH);
}
}
}
/**
* 将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());
}
}
/**
* 计算订单总价
*/
@ApiOperation("删除购物车中商品")
@PostMapping("/delete")
public ApiRestResponse delete(@RequestParam Integer productId) {
List<CartVO> cartVOS = cartService.delete(UserFilter.currentUser.get().getId(), productId);
return ApiRestResponse.success(cartVOS);
}
@ApiOperation("选中商品或取消选中")
@PostMapping("/select")
public ApiRestResponse select(@RequestParam Integer productId, @RequestParam Integer selected) {
List<CartVO> cartVOList = cartService.selectOrNot(UserFilter.currentUser.get().getId(), productId, selected);
return ApiRestResponse.success(cartVOList);
}
@ApiOperation("商品全选或取消全选")
@PostMapping("selectAll")
public ApiRestResponse selectAll(@RequestParam Integer selected) {
List<CartVO> cartVOList = cartService.selectAll(UserFilter.currentUser.get().getId(), selected);
return ApiRestResponse.success(cartVOList);
}
}
/**
* 描述:分类控制器
*/
@RestController
public class CategoryController {
private final CategoryService categoryService;
public CategoryController(UserService userService, CategoryService categoryService) {
this.categoryService = categoryService;
}
@ApiOperation("后台添加目录")
@PostMapping("/admin/category/add")
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;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
@ApiOperation("创建订单")
@PostMapping("/order/create")
public ApiRestResponse create(@RequestBody @Valid CreateOrderRequest createOrderRequest) {
String orderCode = orderService.create(createOrderRequest);
return ApiRestResponse.success(orderCode);
}
@ApiOperation("前台订单详情")
@GetMapping("/order/detail")
public ApiRestResponse detail(@RequestParam String orderNo) {
OrderVO detail = orderService.detail(orderNo);
}
@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 {
/**
* 描述:分类控制器
*/
@RestController
public class CategoryController {
private final CategoryService categoryService;
public CategoryController(UserService userService, CategoryService categoryService) {
this.categoryService = categoryService;
}
@ApiOperation("后台添加目录")
@PostMapping("/admin/category/add")
public ApiRestResponse<Object> addCategory(@RequestBody @Valid AddCategoryReq categoryReq) throws GobMallException {
categoryService.add(categoryReq);
return ApiRestResponse.success();
}
@ApiOperation("后台更新目录")
@PostMapping("/admin/category/update")
public ApiRestResponse<Object> updateCategory(@RequestBody @Valid UpdateCategoryReq updateCategoryReq) {
Category category = new Category();
BeanUtils.copyProperties(updateCategoryReq, category);
categoryService.update(category);
return ApiRestResponse.success();
}
/**
* 管理员校验过滤器 : 对需要管理员权限的接口进行过滤,过滤拦截没有权限的请求,并返回错误信息
*/
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() {
/***
* 前台商品Controller
*/
@RestController
@RequestMapping("/product")
public class ProductController {
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);
}
}
/**
* 订单service实现类
*/
@Service
public class OrderServiceImpl implements OrderService {
private final Logger log = LoggerFactory.getLogger(OrderServiceImpl.class);
private final CartService cartService;
private final ProductMapper productMapper;
private final CartMapper cartMapper;
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
@Value("${file.upload.ip}")
private String ip;