springboot编写博客系统的点赞功能
时间: 2023-08-03 17:12:02 浏览: 104
实现博客点赞功能的基本思路如下:
1. 定义点赞实体类
```java
@Entity
public class Like {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long userId;
private Long blogId;
// getter, setter and constructor
}
```
2. 创建点赞表
```sql
CREATE TABLE `like` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`user_id` bigint(20) NOT NULL,
`blog_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
```
3. 创建点赞服务类
```java
@Service
public class LikeService {
@Autowired
private LikeRepository likeRepository;
public void like(Long userId, Long blogId) {
Like like = new Like(userId, blogId);
likeRepository.save(like);
}
public void cancelLike(Long userId, Long blogId) {
likeRepository.deleteByUserIdAndBlogId(userId, blogId);
}
}
```
4. 创建点赞控制器
```java
@RestController
public class LikeController {
@Autowired
private LikeService likeService;
@PostMapping("/like")
public void like(@RequestParam Long userId, @RequestParam Long blogId) {
likeService.like(userId, blogId);
}
@PostMapping("/cancel-like")
public void cancelLike(@RequestParam Long userId, @RequestParam Long blogId) {
likeService.cancelLike(userId, blogId);
}
}
```
5. 在博客详情页面中添加点赞按钮
```html
<button onclick="like()">点赞</button>
<button onclick="cancelLike()">取消点赞</button>
<script>
function like() {
$.post("/like?userId=${userId}&blogId=${blogId}", function() {
alert("点赞成功!");
});
}
function cancelLike() {
$.post("/cancel-like?userId=${userId}&blogId=${blogId}", function() {
alert("取消点赞成功!");
});
}
</script>
```
以上就是实现博客点赞功能的基本步骤,具体实现还需要结合具体的业务需求进行调整。
阅读全文