Springboot + Vue 个人博客 后端交互样例

本文介绍如何使用SpringBoot和Vue构建个人博客系统,涵盖前后端交互、数据封装及评论功能实现,通过具体代码样例展示楼中楼评论效果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Springboot + Vue 个人博客 后端交互样例

后端的样例 使用了ResultUtil来进一步封装返回数据
重点在于Comment 和 Reply查询返回的过程 实现楼中楼 评论的效果

目录

Springboot + Vue 个人博客 主目录
Springboot + Vue 个人博客 前端配置
Springboot + Vue 个人博客 后端配置
Springboot + Vue 个人博客 前端交换样例
Springboot + Vue 个人博客 后端交换样例

代码

Github 后端代码
Github 前端代码


1. Result数据的封装

//用于返回互联网数据
public class Result<T> {
    //状态码
    private Integer code;
    //消息
    private String message;
    //具体数据
    private T data;
    
    //省略 constructer getter setter toString
}
public enum ResultEnum {

    SUCCESS(200,"成功"),
    ERROR(404,"出错");

    //状态码
    private Integer code;
    //消息
    private String message;

    //省略 constructer getter setter toString
}    
//用于返回具体result对象
public class ResultUtil{

    //返回成功状态码和消息以及数据
    public static Result success(Object data){
        return new Result(ResultEnum.SUCCESS.getCode(),ResultEnum.SUCCESS.getMessage(),data);
    }

    //返回错误状态码和消息以及数据
    public static Result error(Object data){
        return new Result(ResultEnum.ERROR.getCode(),ResultEnum.ERROR.getMessage(),data);
    }
}



2. Comment(Servcie Controller Mapper)


2.1 com.example.demo.domain.Comment
public class Comment implements Serializable {
    private Integer id;         //评论id
    private Integer articleId;  //文章id
    private Integer userId;     //用户id
    private String content;     //文章内容
    private String time;        //时间
    private List<Reply> replyList; //回复列表
}

2.2 com.example.demo.mapper.CommentMapper
@Mapper
@Repository
public interface CommentMapper {
    //  增
    void addComment(Comment comment);
    //  删
    void delComment(Integer id);
    //  查
    Comment findeCommentById(Integer id);
    // 查询评论
    List<Comment> findCommentByArticleId(Integer articleId);
    //  改
    void saveComment(Comment comment);
}

2.3 com.example.demo.service.CommentService
public interface CommentService {
    //  增
    void addComment(Comment comment);
    //  删
    void delComment(Integer id);
    //  查
    Comment findeCommentById(Integer id);
    // 查询评论
    List<Comment> findCommentByArticleId(Integer pageNum,Integer pageSize,Integer articleId);
    //  改
    void saveComment(Comment comment);
}

2.4 com.example.demo.service.impl.CommentServiceImpl
@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private ReplyService replyService;

    // 增
    @Override
    public void addComment(Comment comment) {
        commentMapper.addComment(comment);
    }

    // 删
    @Override
    public void delComment(Integer id) {
        commentMapper.delComment(id);
    }

    // 查
    @Override
    public Comment findeCommentById(Integer id) {
        Comment comment=commentMapper.findeCommentById(id);
        List<Reply> replyList=replyService.findAllReplyByCommentId(comment.getId());
        if(replyList!=null){
            comment.setReplyList(replyList);
        }
        return  comment;
    }

    // 查询评论
    @Override
    public List<Comment> findCommentByArticleId(Integer pageNum,Integer pageSize, Integer articleId) {
        PageHelper.startPage(pageNum,pageSize);
        List <Comment> commentList=commentMapper.findCommentByArticleId(articleId);
        List <Comment> updateList=new ArrayList<Comment>();
        //封装reply对象
        for(int i=0;i<commentList.size();i++){
            Comment comment=commentList.get(i);
            //调用replyService查询部分回复
            List<Reply> replyList=replyService.findPartReplyByCommentId(comment.getId());
            if(replyList!=null){
                comment.setReplyList(replyList);
            }
            updateList.add(comment);
        }
        //返回新的List
        return updateList;
    }

    // 改
    @Override
    public void saveComment(Comment comment) {
        commentMapper.saveComment(comment);
    }
}


2.5 com.example.demo.controller.CommentController
@RestController
@RequestMapping(path="/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    //添加评论
    @PostMapping("/add")
    public Result addComment(@RequestBody  Comment comment){
        System.out.println(comment);
        //commentService.addComment(comment);
        return ResultUtil.success(null);
    }

    //id查询评论
    @GetMapping("/find/{id}")
    public Result findCommentById(@PathVariable("id") Integer id){
        Comment comment=commentService.findeCommentById(id);
        return ResultUtil.success(comment);
    }

    //查询评论
    @GetMapping("/{articleId}/{pageNum}/{pageSize}")
    public Result findComment(@PathVariable("articleId") Integer articleId,
                                     @PathVariable("pageNum") Integer pageNum,
                                     @PathVariable("pageSize") Integer pageSize){
        List<Comment> commentList=commentService.findCommentByArticleId(pageNum,pageSize,articleId);


        return ResultUtil.success(commentList);
    }

    //使用 qs 添加评论
    @PostMapping("/add2")
    public Result addComment(@RequestParam("articleId") Integer articleId,
                             @RequestParam("userId") Integer userId,
                             @RequestParam("time") String time,
                             @RequestParam("content") String content){
        System.out.println(articleId+" "+userId+" "+time+" "+content);
        //commentService.addComment(comment);
        return ResultUtil.success(null);
    }
}

2.6 rescources.mapper.CommentMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.example.demo.mapper.CommentMapper">
    <resultMap id="commentMap" type="com.example.demo.domain.Comment">
        <id property="id" column="id"></id>
        <result property="articleId" column="article_id"></result>
        <result property="userId" column="user_id"></result>
        <result property="articleId" column="article_id"></result>
        <result property="time" column="time"></result>
    </resultMap>


<!--    //  增-->
<!--    void addComment(Comment comment); insert into comment(xxx,xxx) values(xxx,xxx)-->
    <insert id="addComment" parameterType="com.example.demo.domain.Comment">
        insert into comment
        <trim prefix="(" suffix=")" suffixOverrides=",">
            <if test="articleId!=null">
                article_id,
            </if>
            <if test="userId!=null">
                user_id,
            </if>
            <if test="content!=null">
                content,
            </if>
            <if test="time!=null">
                time,
            </if>
        </trim>
        <trim prefix="values(" suffix=")" suffixOverrides=",">
            <if test="articleId!=null">
                #{articleId},
            </if>
            <if test="userId!=null">
                #{userId},
            </if>
            <if test="content!=null">
                #{content},
            </if>
            <if test="time!=null">
                #{time},
            </if>
        </trim>
    </insert>

<!--    //  删-->
<!--    void delComment(Integer id);-->
    <delete id="delComment" parameterType="java.lang.Integer">
        delete from comment where id = #{id}
    </delete>

<!--    //  查-->
<!--    Comment findeCommentById(Integer id);-->
    <select id="findeCommentById" parameterType="java.lang.Integer" resultType="com.example.demo.domain.Comment">
        select * from comment where id = #{id}
    </select>

<!--    // 查询评论 List<Comment> findCommentByArticleId(Integer ArticleId);-->
    <select id="findCommentByArticleId" parameterType="java.lang.Integer" resultType="com.example.demo.domain.Comment">
        select * from comment where article_id = #{articleId}
    </select>

<!--    //  改-->
<!--    void saveComment(Comment comment); update comment set xx=xx,xx=xx where id = xx-->
    <update id="saveComment" parameterType="com.example.demo.domain.Comment">
        update comment
        <trim prefix="set" suffixOverrides=",">
            <if test="articleId!=null">
                article_id = #{articleId},
            </if>
            <if test="userId!=null">
                user_id = #{userId},
            </if>
            <if test="content!=null">
                content = #{content},
            </if>
            <if test="time!=null">
                time = #{time},
            </if>
        </trim>
        where id = #{id}
    </update>
</mapper>
### 构建基于Spring BootVue个人信息管理系统 #### 项目概述 构建一个完整的个人信息管理系统涉及前后端分离架构的设计。前端采用Vue.js框架负责视图层交互逻辑;后端则利用Spring Boot提供RESTful API服务,处理业务逻辑并连接数据库。 #### 技术栈选择 - **前端**: Vue CLI作为脚手架工具快速搭建单页面应用(SPA),Element UI组件库提升界面美观度。 - **后端**: 使用Spring Initializr初始化Spring Boot工程,集成Lombok减少板代码量,通过MyBatis操作MySQL完成数据持久化[^2]。 #### 工程目录结构规划 合理的文件夹布局有助于团队协作以及后期维护: ``` personal-info-management/ ├── backend/ # 后端源码根目录 │ ├── src/main/java/com/example/demo/ │ │ └── controller # 控制器类存放处 │ │ └── service # 服务接口定义和服务实现类位置 │ │ └── mapper # MyBatis映射文件所在路径 │ │ └── entity # 数据实体Bean对象保存区 │ └── resources # 配置资源文件夹 └── frontend/ # 前端源码根目录 ├── public # 公共静态资源放置点 ├── src # 主要JavaScript/CSS等编写区域 └── assets # 图片、字体等素材集散地 └── components # 可复用UI部件仓库 └── views # 页面级别的Vue集合 └── router # 路由配置表单 └── store # Vuex状态管理模式下的store容器 ``` #### 用户模块功能描述 针对用户管理部分,主要涵盖注册、登录验证、个人资料编辑等功能点。为了保障安全性,在传输敏感信息前需对其进行加密处理,并设置相应的访问权限控制机制来保护私密内容不被未授权者获取[^1]。 ```javascript // 登录请求示 (frontend/src/api/user.js) import axios from 'axios'; export function login(data) { return axios({ url: '/api/auth/login', method: 'post', data, }); } ``` ```java // 用户控制器 (backend/src/main/java/com/example/demo/controller/UserController.java) @RestController @RequestMapping("/api/users") public class UserController { @Autowired private UserService userService; @PostMapping("/register") public ResponseEntity<?> register(@RequestBody UserDTO userDto){ try{ userService.register(userDto); return new ResponseEntity<>(HttpStatus.CREATED); }catch(Exception e){ return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); } } // 更多API... } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值