登录
首页 >  文章 >  java教程

Java实现文章收藏功能教程

时间:2026-01-20 21:41:42 284浏览 收藏

一分耕耘,一分收获!既然都打开这篇《Java实现简易文章收藏功能指南》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新文章相关的内容,希望对大家都有所帮助!

答案:通过数据库设计收藏表、Spring Boot实现后端接口、前端Ajax交互完成文章收藏功能,支持收藏状态查询与切换,并建议结合登录校验与Redis优化性能。

在Java中如何开发简易文章收藏功能_文章收藏模块开发指南

在Java Web项目中实现一个简易的文章收藏功能,可以帮助用户保存感兴趣的内容,提升交互体验。这个模块涉及前端页面、后端逻辑和数据库设计三部分协同工作。下面介绍如何一步步开发这样一个文章收藏功能。

1. 数据库设计:创建收藏表

收藏功能的核心是记录“哪个用户收藏了哪篇文章”。需要一张收藏关系表来维护这种多对多关系。

示例SQL语句:
CREATE TABLE article_favorite (
    id BIGINT PRIMARY KEY AUTO_INCREMENT,
    user_id BIGINT NOT NULL,
    article_id BIGINT NOT NULL,
    create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
    UNIQUE KEY uk_user_article (user_id, article_id)
);

说明: - user_id:用户ID,关联用户表 - article_id:文章ID,关联文章表 - uk_user_article:唯一索引,防止重复收藏

2. 后端接口设计(基于Spring Boot)

使用Spring MVC构建RESTful接口,处理收藏与取消收藏请求。

实体类 ArticleFavorite:

public class ArticleFavorite {
    private Long id;
    private Long userId;
    private Long articleId;
    private LocalDateTime createTime;
    // getter/setter
}

Controller 层:

@RestController
@RequestMapping("/api/favorites")
public class FavoriteController {
<pre class="brush:java;toolbar:false;">@Autowired
private FavoriteService favoriteService;

// 收藏或取消收藏
@PostMapping
public ResponseEntity<String> toggleFavorite(@RequestBody Map<String, Long> payload) {
    Long userId = payload.get("userId");
    Long articleId = payload.get("articleId");
    try {
        favoriteService.toggleFavorite(userId, articleId);
        return ResponseEntity.ok("操作成功");
    } catch (Exception e) {
        return ResponseEntity.badRequest().body("操作失败:" + e.getMessage());
    }
}

// 查询某文章是否已被用户收藏
@GetMapping("/status")
public ResponseEntity<Boolean> isFavorited(@RequestParam Long userId, @RequestParam Long articleId) {
    boolean favorited = favoriteService.isFavorited(userId, articleId);
    return ResponseEntity.ok(favorited);
}

}

Service 层逻辑:

@Service
public class FavoriteService {
<pre class="brush:java;toolbar:false;">@Autowired
private ArticleFavoriteMapper favoriteMapper;

public void toggleFavorite(Long userId, Long articleId) {
    if (isFavorited(userId, articleId)) {
        favoriteMapper.deleteByUserAndArticle(userId, articleId);
    } else {
        ArticleFavorite favorite = new ArticleFavorite();
        favorite.setUserId(userId);
        favorite.setArticleId(articleId);
        favoriteMapper.insert(favorite);
    }
}

public boolean isFavorited(Long userId, Long articleId) {
    return favoriteMapper.countByUserAndArticle(userId, articleId) > 0;
}

}

Mapper(使用MyBatis):

@Mapper
public interface ArticleFavoriteMapper {
    void insert(ArticleFavorite favorite);
    void deleteByUserAndArticle(Long userId, Long articleId);
    int countByUserAndArticle(Long userId, Long articleId);
}

3. 前端交互实现

前端通过Ajax调用后端接口,动态更新收藏状态。

HTML按钮示例:

<button id="favoriteBtn" onclick="toggleFavorite()"><span id="favoriteText">收藏</span></button>

JavaScript脚本:

let isFavorited = false;
const userId = 123; // 实际应从登录上下文获取
const articleId = 456;
<p>// 页面加载时查询当前收藏状态
fetch(<code>/api/favorites/status?userId=${userId}&amp;articleId=${articleId}</code>)
.then(res => res.json())
.then(favorited => {
isFavorited = favorited;
updateButton();
});</p><p>function toggleFavorite() {
fetch('/api/favorites', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ userId, articleId })
}).then(() => {
isFavorited = !isFavorited;
updateButton();
});
}</p><p>function updateButton() {
document.getElementById('favoriteText').textContent = isFavorited ? '已收藏' : '收藏';
}</p>

4. 安全与优化建议

  • 确保用户登录后才能操作,可通过拦截器校验session或JWT token
  • 接口参数需做非空和合法性校验
  • 高频访问可引入Redis缓存收藏状态,减轻数据库压力
  • 提供批量查询接口,如“获取用户所有收藏文章”
  • 添加分页支持,避免一次性加载过多数据

基本上就这些。一个简洁可用的文章收藏模块就能跑起来。核心在于状态切换逻辑清晰,前后端配合顺畅。后续可根据需求扩展通知、分类收藏等功能。

本篇关于《Java实现文章收藏功能教程》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于文章的相关知识,请关注golang学习网公众号!

前往漫画官网入口并下载 ➜
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>