携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第11天,点击查看活动详情
帖子详情
在首页的帖子列表页面上,可以随便选一个帖子,然后点它的标题,我们就可以打开一个显示帖子详细信息的页面,然后把帖子的详细内容显示完整,这就是帖子详情的功能。
- 数据访问层(dao)
dao接口中增加一个查询帖子的功能:
DiscussPost selectDiscussPostById(int id);
/*
根据帖子id查询帖子的详细内容
*/
然后编写它对应的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>
- 业务层(service)
在DiscussPostService中增加一个查询帖子的方法
public DiscussPost findDiscussPostById(int id){
return discussPostMapper.selectDiscussPostById(id);
}
- 表现层(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中的查询帖子的方法。
discuss-detail.html:
接着我们要处理详情页面数据的展现
测试