3.3 帖子详情

88 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第11天,点击查看活动详情

帖子详情

image-20220715164957608

在首页的帖子列表页面上,可以随便选一个帖子,然后点它的标题,我们就可以打开一个显示帖子详细信息的页面,然后把帖子的详细内容显示完整,这就是帖子详情的功能。

  1. 数据访问层(dao)

dao接口中增加一个查询帖子的功能:

DiscussPost selectDiscussPostById(int id);
/*
根据帖子id查询帖子的详细内容
 */

image-20220715170009432

然后编写它对应的mapper配置文件

<sql id="selectFields" >
  id, user_id, title, content, type, status, create_time, comment_count, score
</sql>

<select id="selectDiscussPostById" resultType="com.nowcoder.community.entity.DiscussPost" parameterType="Integer">
    select <include refid="selectFields"></include>
    from discuss_post
    where id = #{id}
</select>

image-20220715170328372

  1. 业务层(service)

在DiscussPostService中增加一个查询帖子的方法

public DiscussPost findDiscussPostById(int id){
    return discussPostMapper.selectDiscussPostById(id);
}

image-20220715170551475

  1. 表现层(controller和html)

DiscussPostController:

@Autowired
private UserService userService;

@RequestMapping(path = "/detail/{discussPostId}", method = RequestMethod.GET)
public String getDiscussPost(@PathVariable("discussPostId") int discussPostId, Model model){
    // 由id查询帖子
    DiscussPost post = discussPostService.findDiscussPostById(discussPostId);
    model.addAttribute("post", post);
    // 由于discussPost显示的只有用户的id,我们显示在页面上的肯定是用户的username而不是id,所以我们还需要查一下username
    User user = userService.findUserById(post.getUserId());
    model.addAttribute("user", user);

    return "/site/discuss-detail";
}

index.html:

我们要在首页的每一个帖子上的标题上加一个链接,链接能够访问到上面DiscussPostController中的查询帖子的方法。

image-20220715172853067

discuss-detail.html:

接着我们要处理详情页面数据的展现

image-20220715174406096

image-20220715174442425

image-20220715174624907

image-20220715174704274

测试

image-20220715174824972

image-20220715174851109