Spring Boot项目学习15之我的主页和用户中心模块

1.我的主页模块

index.html页面右上角个人信息按钮可以跳转至我的首页。
在这里插入图片描述

1.1 BBSUserController控制器

这里需要查询用户的基本信息,然后用户发过的帖子信息,以及收藏过的帖子信息。
BBSUserController

    /**
     * 跳转我的主页
     * @param request
     * @return
     */
    @GetMapping("/myCenter")
    public String myCenterPage(HttpServletRequest request) {

        //基本用户信息
        BBSUser currentUser = (BBSUser) request.getSession().getAttribute(Constants.USER_SESSION_KEY);

        //我发的贴
        List<BBSPost> myBBSPostList = bbsPostService.getMyBBSPostList(currentUser.getUserId());
        int myBBSPostCount = 0;
        if (!CollectionUtils.isEmpty(myBBSPostList)) {
            myBBSPostCount = myBBSPostList.size();
        }

        //我收藏的贴
        List<BBSPost> collectRecords = bbsPostCollectService.getCollectRecordsByUserId(currentUser.getUserId());
        int myCollectBBSPostCount = 0;
        if (!CollectionUtils.isEmpty(collectRecords)) {
            myCollectBBSPostCount = collectRecords.size();
        }

        request.setAttribute("myBBSPostList", myBBSPostList);
        request.setAttribute("myBBSPostCount", myBBSPostCount);
        request.setAttribute("collectRecords", collectRecords);
        request.setAttribute("myCollectBBSPostCount", myCollectBBSPostCount);
        request.setAttribute("bbsUser", currentUser);
        return "user/index";
    }

首先通过session对象获取,存储在其中的用户信息;然后通过用户id查询该用户发过的帖子信息,最后通过用户id查询用户收藏过的帖子。

1.2 业务层

BBSPostService

    /**
     * 根据userId查询发布的所有帖子
     *
     * @return
     */
    List<BBSPost> getMyBBSPostList(Long userId);
    @Override
    public List<BBSPost> getMyBBSPostList(Long userId) {
        return bbsPostMapper.getMyBBSPostList(userId, "all");
    }

BBSPostCollectService

    /**
     * 获取收藏的帖子列表
     *
     * @param userId
     * @return
     */
    List<BBSPost> getCollectRecordsByUserId(Long userId);
    @Override
    public List<BBSPost> getCollectRecordsByUserId(Long userId) {

        List<BBSPostCollect> bbsPostCollects = bbsPostCollectMapper.listByUserId(userId);

        if (!CollectionUtils.isEmpty(bbsPostCollects)) {
            List<Long> postIds = bbsPostCollects.stream().map(BBSPostCollect::getPostId).collect(Collectors.toList());
            List<BBSPost> bbsPosts = bbsPostMapper.selectByPrimaryKeys(postIds);
            return bbsPosts;
        }

        return null;
    }

1.3 数据持久层

BBSPostMapper

List<BBSPost> getMyBBSPostList(@Param("userId") Long userId, @Param("period") String period);

List<BBSPost> selectByPrimaryKeys(@Param("postIds")List<Long> postIds);
    <select id="getMyBBSPostList" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from tb_bbs_post
        where publish_user_id = #{userId} and post_status = 1
        <choose>
            <!-- 近30天 -->
            <when test="period!=null and period=='recent'">
                and create_time &gt; DATE_SUB(now(), INTERVAL 31 DAY)
            </when>
            <!-- 全部数据 -->
            <otherwise>
            </otherwise>
        </choose>
        order by post_id desc limit 10
    </select>

    <select id="selectByPrimaryKeys" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List"/>
        from tb_bbs_post
        where post_status=1 and post_id in
        <foreach item="postId" collection="postIds" open="(" separator="," close=")">
            #{postId,jdbcType=BIGINT}
        </foreach>
    </select>

BBSPostCollectMapper

 List<BBSPostCollect> listByUserId(@Param("userId") Long userId);
    <select id="listByUserId" resultMap="BaseResultMap">
        select
        <include refid="Base_Column_List" />
        from tb_post_collect_record
        where user_id = #{userId,jdbcType=BIGINT}
    </select>

1.4 前端首页

在user文件夹下创建index.html页面。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="header::head-fragment('用户中心')">
</head>
<body>
<div th:replace="header::header-fragment"></div>

<div class="layui-container fly-marginTop fly-user-main">
    <ul class="layui-nav layui-nav-tree layui-inline" lay-filter="user">
        <li class="layui-nav-item">
            <a th:href="@{${'/userCenter/'+bbsUser.userId}}">
                <i class="layui-icon">&#xe609;</i>
                我的主页
            </a>
        </li>
        <li class="layui-nav-item layui-this">
            <a th:href="@{/myCenter}">
                <i class="layui-icon">&#xe612;</i>
                用户中心
            </a>
        </li>
        <li class="layui-nav-item">
            <a th:href="@{/userSet}">
                <i class="layui-icon">&#xe620;</i>
                基本设置
            </a>
        </li>
    </ul>

    <div class="fly-panel fly-panel-user" pad20>
        <div class="layui-tab layui-tab-brief" lay-filter="user">
            <ul class="layui-tab-title" id="LAY_mine">
                <li data-type="mine-jie" lay-id="index" class="layui-this">我发的帖(<span th:text="${myBBSPostCount}">11</span></li>
                <li data-type="collection" data-url="/collection/find/" lay-id="collection">我收藏的帖(<span th:text="${myCollectBBSPostCount}">16</span></li>
            </ul>
            <div class="layui-tab-content" style="padding: 20px 0;">
                <div class="layui-tab-item layui-show">

                    <th:block th:if="${#lists.isEmpty(myBBSPostList)}">
                        <!-- 无数据时 -->
                        <div class="fly-none">没有相关数据</div>
                    </th:block>

                    <th:block th:unless="${#lists.isEmpty(myBBSPostList)}">
                        <ul class="mine-view jie-row">
                            <th:block th:each="bbsPost : ${myBBSPostList}">
                                <li>
                                    <a class="jie-title" th:href="@{${'/detail/'+bbsPost.postId}}" target="_blank" th:text="${bbsPost.postTitle}">My-BBS</a>
                                    <i th:text="${#dates.format(bbsPost.createTime, 'yyyy/MM/dd HH:mm:ss')}">2021/08/01</i>
                                    <a class="mine-edit" th:href="@{${'/editPostPage/'+bbsPost.postId}}">编辑</a>
                                    <a class="mine-del" href="##" th:onclick="'delPost('+${bbsPost.postId}+')'">删除</a>
                                    <em><th:block th:text="${bbsPost.postViews}"></th:block>阅/<th:block th:text="${bbsPost.postComments}"></th:block></em>
                                </li>
                            </th:block>
                        </ul>
                    </th:block>
                    <div id="LAY_page"></div>
                </div>
                <div class="layui-tab-item">

                    <th:block th:if="${#lists.isEmpty(collectRecords)}">
                        <!-- 无数据时 -->
                        <div class="fly-none">没有相关数据</div>
                    </th:block>

                    <th:block th:unless="${#lists.isEmpty(collectRecords)}">
                        <ul class="mine-view jie-row">
                            <th:block th:each="bbsPost : ${collectRecords}">
                                <li>
                                    <a class="jie-title" th:href="@{${'/detail/'+bbsPost.postId}}" target="_blank" th:text="${bbsPost.postTitle}">My-BBS</a>
                                    <em><th:block th:text="${bbsPost.postCollects}"></th:block>收藏</em>
                                </li>
                            </th:block>
                        </ul>
                    </th:block>
                    <div id="LAY_page1"></div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="fly-footer">
    <p>My-BBS社区 2021 &copy; <a href="#" target="_blank">picacho</a></p>
</div>

<script th:src="@{/layui/layui.js}"></script>
<script type="text/javascript">
    layui.use(['layer', 'element', 'jquery'], function () {
        var layer = layui.layer, $ = layui.$, element = layui.element;
        var device = layui.device();
        //阻止IE7以下访问
        if (device.ie && device.ie < 8) {
            layer.alert('如果您非得使用 IE 浏览器访问社区,那么请使用 IE8+');
        }
        //搜索
        $('.fly-search').on('click', function () {
            layer.open({
                type: 1
                , title: false
                , closeBtn: false
                //,shade: [0.1, '#fff']
                , shadeClose: true
                , maxWidth: 10000
                , skin: 'fly-layer-search'
                , content: ['<form action="/index">'
                    , '<input autocomplete="off" placeholder="搜索内容,回车跳转" type="text" name="keyword">'
                    , '</form>'].join('')
                , success: function (layero) {
                    var input = layero.find('input');
                    input.focus();
                    layero.find('form').submit(function () {
                        var val = input.val();
                        if (val.replace(/\s/g, '') === '') {
                            return false;
                        }
                        input.val(input.val());
                    });
                }
            })
        });

        window.delPost = function (postId) {
            var $ = layui.$;
            $.ajax({
                type: 'POST',//方法类型
                url: '/delPost/'+postId,
                success: function (result) {
                    if (result.resultCode == 200) {
                        layer.confirm('删除成功!将刷新本页面...', {icon: 3, skin: 'layui-layer-molv',title:'提示'}, function(index){
                            layer.close(index);
                            window.location.reload();
                        });
                    } else {
                        layer.msg(result.message);
                    }
                    ;
                },
                error: function () {
                    layer.alert('操作失败!', {title: '提醒', skin: 'layui-layer-molv', icon: 2});
                }
            });
        }
    });
</script>
</body>
</html>

1.5 测试效果

在这里插入图片描述

1.6 删除帖子功能

在这里插入图片描述

        window.delPost = function (postId) {
            var $ = layui.$;
            $.ajax({
                type: 'POST',//方法类型
                url: '/delPost/'+postId,
                success: function (result) {
                    if (result.resultCode == 200) {
                        layer.confirm('删除成功!将刷新本页面...', {icon: 3, skin: 'layui-layer-molv',title:'提示'}, function(index){
                            layer.close(index);
                            window.location.reload();
                        });
                    } else {
                        layer.msg(result.message);
                    }
                    ;
                },
                error: function () {
                    layer.alert('操作失败!', {title: '提醒', skin: 'layui-layer-molv', icon: 2});
                }
            });
        }

BBSPostController

    @PostMapping("/delPost/{postId}")
    @ResponseBody
    public Result delPost(@PathVariable("postId") Long postId,
                          HttpSession httpSession) {
        if (null == postId || postId < 0) {
            return ResultGenerator.genFailResult("postId参数错误");
        }
        BBSUser bbsUser = (BBSUser) httpSession.getAttribute(Constants.USER_SESSION_KEY);
        if (bbsPostService.delBBSPost(bbsUser.getUserId(), postId) > 0) {
            return ResultGenerator.genSuccessResult();
        } else {
            return ResultGenerator.genFailResult("请求失败,请检查参数及账号是否有操作权限");
        }
    }

BBSPostService

    /**
     * 删除帖子
     *
     * @param userId
     * @param postId
     * @return
     */
    int delBBSPost(Long userId, Long postId);
    @Override
    public int delBBSPost(Long userId, Long postId) {
        BBSUser bbsUser = bbsUserMapper.selectByPrimaryKey(userId);

        if (bbsUser == null || bbsUser.getUserStatus().intValue() == 1) {
            //账号已被封禁
            return 0;
        }

        BBSPost bbsPost = bbsPostMapper.selectByPrimaryKey(postId);
        // 对象不为空且发帖人为当前登录用户才可以删除
        if (bbsPost != null && bbsPost.getPublishUserId().equals(userId)) {
            return bbsPostMapper.deleteByPrimaryKey(postId);
        }
        return 0;
    }

BBSPostMapper

int deleteByPrimaryKey(Long postId);
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Long">
        delete
        from tb_bbs_post
        where post_id = #{postId,jdbcType=BIGINT}
    </delete>

1.7 测试效果

在这里插入图片描述
在这里插入图片描述

1.8 退出登陆

在这里插入图片描述
BBSUserController

    @GetMapping("/logout")
    public String logout(HttpSession httpSession) {
        httpSession.removeAttribute(Constants.USER_SESSION_KEY);
        return "user/login";
    }

2.我的中心模块

该页面主要展示用户发布的帖子以及恢复的评论。
在这里插入图片描述
BBSUserController

    @GetMapping("/userCenter/{userId}")
    public String userCenterPage(HttpServletRequest request, @PathVariable("userId") Long userId) {
        //基本用户信息
        BBSUser bbsUser = bbsUserService.getUserById(userId);
        if (bbsUser == null) {
            return "error/error_404";
        }

        //近期发布的帖子
        List<BBSPost> recentPostList = bbsPostService.getRecentPostListByUserId(userId);

        //近期回复的内容
        List<RecentCommentListEntity> recentCommentList = bbsPostCommentService.getRecentCommentListByUserId(userId);

        request.setAttribute("bbsUser", bbsUser);
        request.setAttribute("recentPostList", recentPostList);
        request.setAttribute("recentCommentList", recentCommentList);
        return "user/home";
    }

2.1 创建RecentCommentListEntity实体类

RecentCommentListEntity

/**
 * 个人中心最近评论列表-实体类
 * 页面展示时需要的字段与评论实体类不同,因此新增了这个类
 */
public class RecentCommentListEntity {

    private Long postId;

    private String postTitle;

    private String commentBody;

    private Date commentCreateTime;

    public Long getPostId() {
        return postId;
    }

    public void setPostId(Long postId) {
        this.postId = postId;
    }

    public String getPostTitle() {
        return postTitle;
    }

    public void setPostTitle(String postTitle) {
        this.postTitle = postTitle;
    }

    public String getCommentBody() {
        return commentBody;
    }

    public void setCommentBody(String commentBody) {
        this.commentBody = commentBody;
    }

    public Date getCommentCreateTime() {
        return commentCreateTime;
    }

    public void setCommentCreateTime(Date commentCreateTime) {
        this.commentCreateTime = commentCreateTime;
    }
}

2.2 业务层

BBSPostService

    /**
     * 根据userId获取最近发帖列表
     *
     * @param userId
     * @return
     */
    List<BBSPost> getRecentPostListByUserId(Long userId);
    @Override
    public List<BBSPost> getRecentPostListByUserId(Long userId) {
        return bbsPostMapper.getMyBBSPostList(userId, "recent");
    }

BBSPostCommentService

    /**
     * 个人中心-最近评论列表
     *
     * @param userId
     * @return
     */
    List<RecentCommentListEntity> getRecentCommentListByUserId(Long userId);
   @Override
    public List<RecentCommentListEntity> getRecentCommentListByUserId(Long userId) {
        List<BBSPostComment> recentCommentList = bbsPostCommentMapper.getRecentCommentListByUserId(userId);
        List<RecentCommentListEntity> recentCommentListEntities = new ArrayList<>();
        if (!CollectionUtils.isEmpty(recentCommentList)) {
            recentCommentListEntities = BeanUtil.copyList(recentCommentList, RecentCommentListEntity.class);
            //帖子id
            List<Long> postIds = recentCommentList.stream().map(BBSPostComment::getPostId).collect(Collectors.toList());
            //查询帖子数据
            List<BBSPost> bbsPosts = bbsPostMapper.selectByPrimaryKeys(postIds);
            if (!CollectionUtils.isEmpty(bbsPosts)) {
                //封装帖子数据
                Map<Long, BBSPost> bbsPostMap = bbsPosts.stream().collect(Collectors.toMap(BBSPost::getPostId, Function.identity(), (entity1, entity2) -> entity1));
                for (RecentCommentListEntity recentCommentListEntity : recentCommentListEntities) {
                    if (bbsPostMap.containsKey(recentCommentListEntity.getPostId())) {
                        //设置帖子标题
                        BBSPost bbsPost = bbsPostMap.get(recentCommentListEntity.getPostId());
                        recentCommentListEntity.setPostTitle(bbsPost.getPostTitle());
                    }
                }
            }
        }
        return recentCommentListEntities;
    }

持久层就不详细阐述了。

2.3 前端页面

在user文件下创建home.html。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="header::head-fragment('用户主页')">
</head>
<body style="margin-top: 65px;">

<div th:replace="header::header-fragment"></div>

<div class="fly-home fly-panel">
    <img th:src="@{${bbsUser.headImgUrl}}" th:alt="${bbsUser.nickName}">
    <h1>
        <th:block th:text="${bbsUser.nickName}">picacho</th:block>
        <th:block th:if="${bbsUser.gender==''}">
            <i class="iconfont icon-nan"></i>
        </th:block>
        <th:block th:if="${bbsUser.gender==''}">
            <i class="iconfont icon-nv"></i>
        </th:block>
        <th:block th:if="${bbsUser.gender=='未知'}">
            <i class="iconfont icon-biaoqing"></i>
        </th:block>
    </h1>

    <p class="fly-home-info">
        <i class="iconfont icon-biaoqing1"></i><span>
        <th:block th:if="${bbsUser.userStatus==0}">账号正常
        </th:block>
        <th:block th:if="${bbsUser.userStatus==1}">账号已被封
        </th:block>
        </span>
        <i class="iconfont icon-shijian"></i><span th:text="${#dates.format(bbsUser.createTime, 'yyyy-MM-dd')+' 加入'}"/>
        <i class="iconfont icon-chengshi"></i><span th:text="${bbsUser.location}">武汉</span>
    </p>

    <p class="fly-home-sign" th:text="${bbsUser.introduce}">加油,努力</p>
</div>

<div class="layui-container">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md6 fly-home-jie">
            <div class="fly-panel">
                <h3 class="fly-panel-title">
                    <th:block th:text="${bbsUser.nickName}"></th:block>
                    近期发布的帖子
                </h3>
                <ul class="jie-row">

                    <th:block th:unless="${#lists.isEmpty(recentPostList)}">
                        <th:block th:each="bbsPost : ${recentPostList}">
                            <li>
                                <a th:href="@{${'/detail/'+bbsPost.postId}}"
                                   th:text="${bbsPost.postTitle}">My-BBS</a>
                                <i th:text="${#dates.format(bbsPost.createTime, 'yyyy/MM/dd HH:mm:ss')}">2021/08/01</i>
                                <em class="layui-hide-xs">
                                    <th:block th:text="${bbsPost.postViews}"></th:block>
                                    阅/
                                    <th:block th:text="${bbsPost.postComments}"></th:block></em>
                            </li>
                        </th:block>
                    </th:block>

                    <th:block th:if="${#lists.isEmpty(recentPostList)}">
                        <!-- 无数据时 -->
                        <div class="fly-none" style="min-height: 50px; padding:30px 0; height:auto;">
                            <i style="font-size:14px;">没有发布任何帖子</i></div>
                    </th:block>

                </ul>
            </div>
        </div>

        <div class="layui-col-md6 fly-home-da">
            <div class="fly-panel">
                <h3 class="fly-panel-title">
                    <th:block th:text="${bbsUser.nickName}">picacho</th:block>
                    最近的评论
                </h3>
                <ul class="home-jieda">
                    <th:block th:if="${#lists.isEmpty(recentCommentList)}">
                        <div class="fly-none" style="min-height: 50px; padding:30px 0; height:auto;"><span>近期没有回复</span>
                        </div>
                    </th:block>

                    <th:block th:unless="${#lists.isEmpty(recentCommentList)}">
                        <th:block th:each="recentComment : ${recentCommentList}">
                            <li>
                                <p>
                                    <span th:text="${#dates.format(recentComment.commentCreateTime, 'yyyy/MM/dd HH:mm:ss')}">1分钟前</span><a th:href="@{${'/detail/'+recentComment.postId}}"
                                        th:text="${recentComment.postTitle}" target="_blank">My-BBS</a>中评论:
                                </p>
                                <div class="home-dacontent" th:text="${recentComment.commentBody}">
                                </div>
                            </li>
                        </th:block>
                    </th:block>
                </ul>
            </div>
        </div>
    </div>
</div>

<div class="fly-footer">
    <p>My-BBS社区 2021 &copy; <a href="#" target="_blank">picacho</a></p>
</div>

<script th:src="@{/layui/layui.js}"></script>
<script type="text/javascript">
    layui.use(['layer', 'element', 'jquery'], function () {
        var layer = layui.layer, $ = layui.$, element = layui.element;
        var device = layui.device();
        //阻止IE7以下访问
        if (device.ie && device.ie < 8) {
            layer.alert('如果您非得使用 IE 浏览器访问社区,那么请使用 IE8+');
        }
    });

</script>
</body>
</html>

2.4 测试效果

在这里插入图片描述
项目源码下载地址:源码下载

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

picacho_pkq

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值