云收藏系统|基于Springboot实现云收藏系统(二)

简介: 云收藏系统|基于Springboot实现云收藏系统

云收藏系统|基于Springboot实现云收藏系统(一)https://developer.aliyun.com/article/1423337


四,核心代码展示

package com.favorites.web;
import com.favorites.cache.CacheService;
import com.favorites.comm.Const;
import com.favorites.comm.aop.LoggerManage;
import com.favorites.domain.Collect;
import com.favorites.domain.Favorites;
import com.favorites.domain.Praise;
import com.favorites.domain.enums.CollectType;
import com.favorites.domain.enums.IsDelete;
import com.favorites.domain.result.ExceptionMsg;
import com.favorites.domain.result.Response;
import com.favorites.domain.view.CollectSummary;
import com.favorites.repository.CollectRepository;
import com.favorites.repository.FavoritesRepository;
import com.favorites.repository.PraiseRepository;
import com.favorites.service.CollectService;
import com.favorites.service.FavoritesService;
import com.favorites.service.LookAroundService;
import com.favorites.service.LookRecordService;
import com.favorites.utils.DateUtils;
import com.favorites.utils.HtmlUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
@RestController
@RequestMapping("/collect")
public class CollectController extends BaseController{
  @Autowired
  private CollectRepository collectRepository;
  @Resource
  private FavoritesService favoritesService;
  @Resource
  private CollectService collectService;
  @Resource
  private FavoritesRepository favoritesRepository;
  @Resource
  private PraiseRepository praiseRepository;
  @Autowired
  private CacheService cacheService;
  /**
   * 随便看看
   */
  @Autowired
  private LookAroundService lookAroundService;
  /**
   * 浏览记录
   */
  @Autowired
  private LookRecordService lookRecordService;
  /**
   * 文章收集
   * @param collect
   * @return
   */
  @RequestMapping(value = "/collect", method = RequestMethod.POST)
  @LoggerManage(description="文章收集")
  public Response collect(Collect collect) {    
    try {
      if(StringUtils.isBlank(collect.getLogoUrl()) || collect.getLogoUrl().length()>300){
        collect.setLogoUrl(Const.BASE_PATH + Const.default_logo);
      }
      collect.setUserId(getUserId());
      if(collectService.checkCollect(collect)){
        Collect exist=collectRepository.findByIdAndUserId(collect.getId(), collect.getUserId());
        if(collect.getId()==null){
          collectService.saveCollect(collect);
        }else if(exist==null){//收藏别人的文章
          collectService.otherCollect(collect);
        }else{
          collectService.updateCollect(collect);
        }
      }else{
        return result(ExceptionMsg.CollectExist);
      }
    } catch (Exception e) {
      // TODO: handle exception
      logger.error("collect failed, ", e);
      return result(ExceptionMsg.FAILED);
    }
    return result();
  }
  @RequestMapping(value="/getCollectLogoUrl",method=RequestMethod.POST)
  @LoggerManage(description="获取收藏页面的LogoUrl")
  public String getCollectLogoUrl(String url){
    if(StringUtils.isNotBlank(url)){
      String logoUrl = cacheService.getMap(url);
      if(StringUtils.isNotBlank(logoUrl)){
        return logoUrl;
      }else{
        return Const.default_logo;
      }
    }else{
      return Const.default_logo;
    }
  }
  /**
   * 根据收藏的文章标题和描述推荐收藏夹
   */
  @RequestMapping(value="/getFavoriteResult",method=RequestMethod.POST)
  @LoggerManage(description="获取推荐收藏夹")
  public Map<String,Object> getFavoriteResult(String title,String description){
    Long result = null;
    int faultPosition = 0;
    Map<String,Object> maps = new HashMap<String,Object>();
    List<Favorites> favoritesList = this.favoritesRepository.findByUserIdOrderByLastModifyTimeDesc(getUserId());
    for (int i = 0; i < favoritesList.size(); i++){
      Favorites favorites = favoritesList.get(i);
      if(favorites.getName().indexOf(title) > 0 || favorites.getName().indexOf(description) > 0){
        result = favorites.getId();
      }
      if("未读列表".equals(favorites.getName())){
        faultPosition = i;
      }
    }
    result = result == null ? favoritesList.get(faultPosition).getId() : result;
    maps.put("favoritesResult",result == null ? 0 : result);
    maps.put("favoritesList",favoritesList);
    return maps;
  }
  /**
   * @param page
   * @param size
   * @param type
   * @return
   */
  @RequestMapping(value="/standard/{type}/{favoritesId}/{userId}/{category}")
  @LoggerManage(description="文章列表standard")
  public List<CollectSummary> standard(@RequestParam(value = "page", defaultValue = "0") Integer page,
          @RequestParam(value = "size", defaultValue = "15") Integer size,@PathVariable("type") String type,
          @PathVariable("favoritesId") Long favoritesId,@PathVariable("userId") Long userId,
      @PathVariable("category") String category) {
      Sort sort = new Sort(Direction.DESC, "id");
      Pageable pageable = PageRequest.of(page, size,sort);
      List<CollectSummary> collects = null;
      if("otherpublic".equalsIgnoreCase(type)){
        if(null != favoritesId && 0 != favoritesId){
          collects = collectService.getCollects(type, userId, pageable, favoritesId,getUserId());
        }else{
          collects = collectService.getCollects("others", userId, pageable, null,getUserId());
        }
      }else if(category != null && !"".equals(category) && !"NO".equals(category)){//用于随便看看功能中收藏列表显示
      collects = lookAroundService.queryCollectExplore(pageable,getUserId(),category);
    }else if(type != null && !"".equals(type) && "lookRecord".equals(type)){//用于浏览记录功能中收藏列表显示
      collects =lookRecordService.getLookRecords(this.getUserId(),pageable);
    }else{
        if(null != favoritesId && 0 != favoritesId){
          collects = collectService.getCollects(String.valueOf(favoritesId),getUserId(), pageable,null,null);
        }else{
          collects=collectService.getCollects(type,getUserId(), pageable,null,null);
        }
      }
    return collects;
  }
  @RequestMapping(value="/lookAround")
  @LoggerManage(description="查看更多lookAround")
  public List<CollectSummary> lookAround(@RequestParam(value = "page", defaultValue = "0") Integer page,
                     @RequestParam(value = "size", defaultValue = "15") Integer size) {
    Sort sort = new Sort(Direction.DESC, "id");
    Pageable pageable = PageRequest.of(page, size, sort);
    List<CollectSummary> collects =lookAroundService.queryCollectExplore(pageable, getUserId(),null);
    return collects;
  }
  /**
   * @param page
   * @param size
   * @param type
   * @return
   */
  @RequestMapping(value="/simple/{type}/{favoritesId}/{userId}/{category}")
  @LoggerManage(description="文章列表simple")
  public List<CollectSummary> simple(@RequestParam(value = "page", defaultValue = "0") Integer page,
          @RequestParam(value = "size", defaultValue = "15") Integer size,@PathVariable("type") String type,
          @PathVariable("favoritesId") Long favoritesId,@PathVariable("userId") Long userId
      ,@PathVariable("category") String category) {
    Sort sort = new Sort(Direction.DESC, "id");
      Pageable pageable = PageRequest.of(page, size,sort);
      List<CollectSummary> collects = null;
      if("otherpublic".equalsIgnoreCase(type)){
        if(null != favoritesId && 0 != favoritesId){
          collects = collectService.getCollects(type, userId, pageable, favoritesId,getUserId());
        }else{
          collects = collectService.getCollects("others", userId, pageable, null,getUserId());
        }
      }else if(category != null && !"".equals(category) && !"NO".equals(category)){//用于随便看看功能中收藏列表显示
      collects = lookAroundService.queryCollectExplore(pageable,getUserId(),category);
    }else{
        if(null != favoritesId && 0 != favoritesId){
          collects = collectService.getCollects(String.valueOf(favoritesId),getUserId(), pageable,null,null);
        }else{
          collects = collectService.getCollects(type,getUserId(), pageable,null,null);
        }
      }
    return collects;
  }
  /**
   * @param id
   * @param type
   */
  @RequestMapping(value="/changePrivacy/{id}/{type}")
  public Response changePrivacy(@PathVariable("id") long id,@PathVariable("type") CollectType type) {
    collectRepository.modifyByIdAndUserId(type, id, getUserId());
    return result();
  }
  /**
   * like and unlike
   * @param id
   * @return
   */
  @RequestMapping(value="/like/{id}")
  @LoggerManage(description="文章点赞或者取消点赞")
  public Response like(@PathVariable("id") long id) {
    try {
      collectService.like(getUserId(), id);
    } catch (Exception e) {
      // TODO: handle exception
      logger.error("文章点赞或者取消点赞异常:",e);
    }
    return result();
  }
  /**
   * @param id
   * @return
   */
  @RequestMapping(value="/delete/{id}")
  public Response delete(@PathVariable("id") long id) {
    Collect collect = collectRepository.findById(id);
    if(null != collect && getUserId()==collect.getUserId()){
      collectRepository.deleteById(id);
      if(null != collect.getFavoritesId() && !IsDelete.YES.equals(collect.getIsDelete())){
        favoritesRepository.reduceCountById(collect.getFavoritesId(), DateUtils.getCurrentTime());
      }
    }
    return result();
  }
  /**
   * @param id
   * @return
   */
  @RequestMapping(value="/detail/{id}")
  public Collect detail(@PathVariable("id") long id) {
    Collect collect=collectRepository.findById(id);
    return collect;
  }
  /**
   * 导入收藏夹
   *
   */
  @RequestMapping("/import")
  @LoggerManage(description="导入收藏夹操作")
  public void importCollect(@RequestParam("htmlFile") MultipartFile htmlFile,String structure,String type){
    try {
      if(StringUtils.isNotBlank(structure)&& IsDelete.YES.toString().equals(structure)){
        // 按照目录结构导入
        Map<String, Map<String, String>> map = HtmlUtil.parseHtmlTwo(htmlFile.getInputStream());
        if(null == map || map.isEmpty()){
          logger.info("未获取到url连接");
          return ;
        }
        for (Entry<String, Map<String, String>> entry : map.entrySet()) {  
            String favoritesName = entry.getKey();
            Favorites favorites = favoritesRepository.findByUserIdAndName(getUserId(), favoritesName);
            if(null == favorites){
              favorites = favoritesService.saveFavorites(getUserId(), favoritesName);
            }
            collectService.importHtml(entry.getValue(), favorites.getId(), getUserId(),type);
        } 
      }else{
        Map<String, String> map = HtmlUtil.parseHtmlOne(htmlFile.getInputStream());
        if(null == map || map.isEmpty()){
          logger.info("未获取到url连接");
          return ;
        }
        // 全部导入到<导入自浏览器>收藏夹
        Favorites favorites = favoritesRepository.findByUserIdAndName(getUserId(), "导入自浏览器");
        if(null == favorites){
          favorites = favoritesService.saveFavorites(getUserId(),"导入自浏览器");
        }
        collectService.importHtml(map, favorites.getId(), getUserId(),type);
      }
    } catch (Exception e) {
      logger.error("导入html异常:",e);
    }
  }
  /**
   * 导出收藏夹
   * @param favoritesId
   * @return
   */
  @RequestMapping("/export")
  @LoggerManage(description="导出收藏夹操作")
  public void export(String favoritesId,HttpServletResponse response){
    if(StringUtils.isNotBlank(favoritesId)){
      try {
        String[] ids = favoritesId.split(",");
        String date = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String fileName= "favorites_" + date + ".html";
        StringBuilder sb = new StringBuilder();
        for(String id : ids){
          try {
            sb = sb.append(collectService.exportToHtml(Long.parseLong(id)));
          } catch (Exception e) {
            logger.error("异常:",e);
          }
        }
        sb = HtmlUtil.exportHtml("云收藏夹", sb);
        response.setCharacterEncoding("UTF-8");  
        response.setHeader("Content-disposition","attachment; filename=" + fileName);
        response.getWriter().print(sb);
      } catch (Exception e) {
        logger.error("异常:",e);
      }
    }
  }
  @RequestMapping(value="/searchMy/{key}")
  public List<CollectSummary> searchMy(Model model,@RequestParam(value = "page", defaultValue = "0") Integer page,
          @RequestParam(value = "size", defaultValue = "20") Integer size, @PathVariable("key") String key) {
    Sort sort = new Sort(Direction.DESC, "id");
      Pageable pageable = PageRequest.of(page, size,sort);
      List<CollectSummary> myCollects=collectService.searchMy(getUserId(),key ,pageable);
    model.addAttribute("myCollects", myCollects);
    logger.info("searchMy end :");
    return myCollects;
  }
  @RequestMapping(value="/searchOther/{key}")
  public List<CollectSummary> searchOther(Model model,@RequestParam(value = "page", defaultValue = "0") Integer page,
          @RequestParam(value = "size", defaultValue = "20") Integer size, @PathVariable("key") String key) {
    Sort sort = new Sort(Direction.DESC, "id");
      Pageable pageable = PageRequest.of(page, size,sort);
      List<CollectSummary> otherCollects=collectService.searchOther(getUserId(), key, pageable);
    logger.info("searchOther end :");
    return otherCollects;
  }
  /**
   * 查询点赞状态及该文章的点赞数量
   */
  @RequestMapping(value="/getPaiseStatus/{collectId}")
  public Map<String,Object> getPraiseStatus(Model model,@PathVariable("collectId") Long collectId){
    Map<String,Object> maps = new HashMap<String,Object>();
    Praise praise = praiseRepository.findByUserIdAndCollectId(getUserId(), collectId);
    Long praiseCount = praiseRepository.countByCollectId(collectId);
    maps.put("status",praise != null ? "praise" : "unpraise");
    maps.put("praiseCount",praiseCount);
    return maps;
  }
}
package com.favorites.web;
import java.util.List;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.favorites.domain.Collect;
import com.favorites.domain.Comment;
import com.favorites.domain.User;
import com.favorites.domain.result.Response;
import com.favorites.repository.CollectRepository;
import com.favorites.repository.CommentRepository;
import com.favorites.repository.UserRepository;
import com.favorites.service.NoticeService;
import com.favorites.utils.DateUtils;
import com.favorites.utils.StringUtil;
@RestController
@RequestMapping("/comment")
public class CommentController extends BaseController{
  @Autowired
  private  CommentRepository CommentRepository;
  @Autowired
  private UserRepository userRepository;
  @Resource
  private NoticeService noticeService;
  @Autowired
  private CollectRepository colloectRepository;
  /**
   * @param comment评论
   * @return
   */
  @RequestMapping(value="/add")
  public Response add(Comment comment) {
    User user = null;
    if (comment.getContent().indexOf("@") > -1) {
      List<String> atUsers = StringUtil.getAtUser(comment.getContent());
      if(atUsers!=null && atUsers.size()>0){
        user = userRepository.findByUserName(atUsers.get(0));
        if (null != user) {
          comment.setReplyUserId(user.getId());
        } else {
          logger.info("为找到匹配:" + atUsers.get(0) + "的用户.");
        }
        String content=comment.getContent().substring(0,comment.getContent().indexOf("@"));
        if(StringUtils.isBlank(content)){
          content=comment.getContent().substring(comment.getContent().indexOf("@")+user.getUserName().length()+1,comment.getContent().length());
        }
        comment.setContent(content);
      }
    }
    comment.setUserId(getUserId());
    comment.setCreateTime(DateUtils.getCurrentTime());
    CommentRepository.save(comment);
    if(null != user){
      // 保存消息通知(回复)
      noticeService.saveNotice(String.valueOf(comment.getCollectId()), "comment", user.getId(), String.valueOf(comment.getId()));
    }else{
      // 保存消息通知(直接评论)
      Collect collect = colloectRepository.findById((long)comment.getCollectId());
      if(null != collect){
        noticeService.saveNotice(String.valueOf(comment.getCollectId()), "comment", collect.getUserId(), String.valueOf(comment.getId()));
      }
    }
    return result();
  }
  /**
   * @param collectId
   * @return
   */
  @RequestMapping(value="/list/{collectId}")
  public List<Comment> list(@PathVariable("collectId") long collectId) {
    List<Comment> comments= CommentRepository.findByCollectIdOrderByIdDesc(collectId);
    return convertComment(comments);
  }
  /**
   * @param id
   * @return
   */
  @RequestMapping(value="/delete/{id}")
  public Response delete(@PathVariable("id") long id) {
    CommentRepository.deleteById(id);
    return result();
  }
  /**
   * 转化时间和用户名
   * @param comments
   * @return
   */
  private List<Comment> convertComment(List<Comment> comments) {
    for (Comment comment : comments) {
      User user = userRepository.findById((long)comment.getUserId());
      comment.setCommentTime(DateUtils.getTimeFormatText(comment.getCreateTime()));
      comment.setUserName(user.getUserName());
      comment.setProfilePicture(user.getProfilePicture());
      if(comment.getReplyUserId()!=null && comment.getReplyUserId()!=0){
         User replyUser = userRepository.findById((long)comment.getReplyUserId());
         comment.setReplyUserName(replyUser.getUserName());
      }
    }
    return comments;
  }
}

五,项目总结

整个系统的开发和实现还是比较有创意的,它很好的解决本地浏览器信息收藏的不方便性,可以通过本次开发的云收藏系统和浏览收藏信息进行共享,并在平台中进行有效的管理和共享,功能还是比较实用且齐全的,是一个优秀的毕业设计项目。系统使用Springboot框架开发,整个界面设计十很简洁大方。

相关文章
|
13天前
|
Java 数据库连接 应用服务中间件
基于springboot的母婴健康交流系统
本平台旨在为新手父母提供专业、系统的婴幼儿健康知识与交流空间,整合权威资源,解决育儿信息碎片化与误导问题,支持经验分享与情感互助,助力科学育儿。
|
10天前
|
JavaScript Java 关系型数据库
基于springboot的电影购票管理系统
本系统基于Spring Boot框架,结合Vue、Java与MySQL技术,实现电影信息管理、在线选座、购票支付等核心功能,提升观众购票体验与影院管理效率,推动电影产业数字化发展。
|
15天前
|
JavaScript Java 关系型数据库
基于springboot的小区车位租售管理系统
针对城市化进程中小区停车难问题,本文设计基于SpringBoot的车位租售管理系统,结合Vue前端与MySQL数据库,实现车位信息数字化、租售流程自动化。系统支持在线查询、申请、支付及数据统计,提升管理效率与用户体验,促进资源优化配置。
|
14天前
|
JavaScript Java 关系型数据库
基于springboot的家政服务预约系统
随着社会节奏加快与老龄化加剧,家政服务需求激增,但传统模式存在信息不对称、服务不规范等问题。基于Spring Boot、Vue、MySQL等技术构建的家政预约系统,实现服务线上化、标准化与智能化,提升用户体验与行业效率,推动家政服务向信息化、规范化发展。
|
9天前
|
存储 JavaScript Java
基于springboot的大学公文收发管理系统
本文介绍公文收发系统的研究背景与意义,分析其在数字化阅读趋势下的必要性。系统采用Vue、Java、Spring Boot与MySQL技术,实现高效、便捷的公文管理与在线阅读,提升用户体验与信息处理效率。
|
11天前
|
人工智能 JavaScript Java
基于springboot的大学生创新能力比赛系统
本研究聚焦大学生能力培养系统,结合AI、大数据、区块链及VR/AR等前沿技术,构建个性化、全过程的能力发展框架。通过Java、Spring Boot、MySQL与Vue技术实现系统开发,旨在提升学生综合素质与社会竞争力,推动高等教育改革与创新发展。
|
18天前
|
搜索推荐 算法 JavaScript
基于springboot的健康饮食营养管理系统
本系统基于Spring Boot、Vue与MySQL技术,融合大数据与AI算法,构建个性化健康饮食管理平台。结合用户身体状况、目标需求,智能推荐营养方案,助力科学饮食与健康管理。
|
12天前
|
JavaScript Java 数据库连接
基于springboot的网球场场地预约系统
本系统基于Vue、Spring Boot、Java等技术,构建智能化网球场预约平台,提升用户体验与场地利用率,推动体育产业数字化发展。
|
15天前
|
JavaScript Java 关系型数据库
基于springboot的校内跑腿管理系统
针对校园跑腿服务效率低、信任难等问题,本研究设计基于Spring Boot与Vue的校内跑腿管理系统,融合MySQL数据库与智能化调度技术,实现任务发布、智能匹配、实时追踪与评价反馈一体化,提升服务效率与质量,助力智慧校园建设。
|
16天前
|
JavaScript Java 关系型数据库
基于springboot的快递分拣管理系统
本系统基于SpringBoot框架,结合Java、MySQL与Vue技术,构建智能化快递分拣管理平台。通过自动化识别、精准分拣与实时跟踪,提升分拣效率与准确性,降低人力成本,推动快递行业向智能化、高效化转型,助力电商物流高质量发展。