5-5:显示系统的通知
创始人
2024-03-24 17:03:01
0
  • 通知列表
    • 显示评论、点赞、关注三种类型的通知。
  • 通知详情
    • 分页显示某一类主题所包含的通知。
  • 未读消息
    • 在页面头部显示所有的未读消息数量
      在这里插入图片描述
      通知存在message表里面

修改MessageMapper.java

package com.nowcoder.community.dao;import com.nowcoder.community.entity.Message;
import org.apache.ibatis.annotations.Mapper;import java.util.List;@Mapper
public interface MessageMapper {// 查询当前用户的会话列表,针对每个会话只返回一条最新的私信.List selectConversations(int userId, int offset, int limit);// 查询当前用户的会话数量.int selectConversationCount(int userId);// 查询某个会话所包含的私信列表.List selectLetters(String conversationId, int offset, int limit);// 查询某个会话所包含的私信数量.int selectLetterCount(String conversationId);// 查询未读私信的数量int selectLetterUnreadCount(int userId, String conversationId);// 新增消息int insertMessage(Message message);// 修改消息的状态int updateStatus(List ids, int status);// 查询某个主题下最新的通知Message selectLatestNotice(int userId, String topic);// 查询某个主题所包含的通知数量int selectNoticeCount(int userId, String topic);// 查询未读的通知的数量int selectNoticeUnreadCount(int userId, String topic);// 查询某个主题所包含的通知列表List selectNotices(int userId, String topic, int offset, int limit);}

massage-mapper.xml



id, from_id, to_id, conversation_id, content, status, create_timefrom_id, to_id, conversation_id, content, status, create_timeinsert into message()values(#{fromId},#{toId},#{conversationId},#{content},#{status},#{createTime})update message set status = #{status}where id in#{id}

MassageService.java

通知和私信存在一个表里

在这里插入代码片`package com.nowcoder.community.service;import com.nowcoder.community.dao.MessageMapper;
import com.nowcoder.community.entity.Message;
import com.nowcoder.community.util.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.util.HtmlUtils;import java.util.List;@Service
public class MessageService {@Autowiredprivate MessageMapper messageMapper;@Autowiredprivate SensitiveFilter sensitiveFilter;public List findConversations(int userId, int offset, int limit) {return messageMapper.selectConversations(userId, offset, limit);}public int findConversationCount(int userId) {return messageMapper.selectConversationCount(userId);}public List findLetters(String conversationId, int offset, int limit) {return messageMapper.selectLetters(conversationId, offset, limit);}public int findLetterCount(String conversationId) {return messageMapper.selectLetterCount(conversationId);}public int findLetterUnreadCount(int userId, String conversationId) {return messageMapper.selectLetterUnreadCount(userId, conversationId);}public int addMessage(Message message) {message.setContent(HtmlUtils.htmlEscape(message.getContent()));message.setContent(sensitiveFilter.filter(message.getContent()));return messageMapper.insertMessage(message);}public int readMessage(List ids) {return messageMapper.updateStatus(ids, 1);}public Message findLatestNotice(int userId, String topic) {return messageMapper.selectLatestNotice(userId, topic);}public int findNoticeCount(int userId, String topic) {return messageMapper.selectNoticeCount(userId, topic);}public int findNoticeUnreadCount(int userId, String topic) {return messageMapper.selectNoticeUnreadCount(userId, topic);}public List findNotices(int userId, String topic, int offset, int limit) {return messageMapper.selectNotices(userId, topic, offset, limit);}}
`

需要把message表中的content字段转化成好读写的格式,还原回JSON格式,还原转义字符

MessageController.java

package com.nowcoder.community.controller;import com.alibaba.fastjson.JSONObject;
import com.nowcoder.community.entity.Message;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.MessageService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
import com.nowcoder.community.util.CommunityUtil;
import com.nowcoder.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;import java.util.*;@Controller
public class MessageController implements CommunityConstant {@Autowiredprivate MessageService messageService;@Autowiredprivate HostHolder hostHolder;@Autowiredprivate UserService userService;// 私信列表@RequestMapping(path = "/letter/list", method = RequestMethod.GET)public String getLetterList(Model model, Page page) {User user = hostHolder.getUser();// 分页信息page.setLimit(5);page.setPath("/letter/list");page.setRows(messageService.findConversationCount(user.getId()));// 会话列表List conversationList = messageService.findConversations(user.getId(), page.getOffset(), page.getLimit());List> conversations = new ArrayList<>();if (conversationList != null) {for (Message message : conversationList) {Map map = new HashMap<>();map.put("conversation", message);map.put("letterCount", messageService.findLetterCount(message.getConversationId()));map.put("unreadCount", messageService.findLetterUnreadCount(user.getId(), message.getConversationId()));int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();map.put("target", userService.findUserById(targetId));conversations.add(map);}}model.addAttribute("conversations", conversations);// 查询未读消息数量int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);model.addAttribute("letterUnreadCount", letterUnreadCount);int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);model.addAttribute("noticeUnreadCount", noticeUnreadCount);return "/site/letter";}@RequestMapping(path = "/letter/detail/{conversationId}", method = RequestMethod.GET)public String getLetterDetail(@PathVariable("conversationId") String conversationId, Page page, Model model) {// 分页信息page.setLimit(5);page.setPath("/letter/detail/" + conversationId);page.setRows(messageService.findLetterCount(conversationId));// 私信列表List letterList = messageService.findLetters(conversationId, page.getOffset(), page.getLimit());List> letters = new ArrayList<>();if (letterList != null) {for (Message message : letterList) {Map map = new HashMap<>();map.put("letter", message);map.put("fromUser", userService.findUserById(message.getFromId()));letters.add(map);}}model.addAttribute("letters", letters);// 私信目标model.addAttribute("target", getLetterTarget(conversationId));// 设置已读List ids = getLetterIds(letterList);if (!ids.isEmpty()) {messageService.readMessage(ids);}return "/site/letter-detail";}private User getLetterTarget(String conversationId) {String[] ids = conversationId.split("_");int id0 = Integer.parseInt(ids[0]);int id1 = Integer.parseInt(ids[1]);if (hostHolder.getUser().getId() == id0) {return userService.findUserById(id1);} else {return userService.findUserById(id0);}}private List getLetterIds(List letterList) {List ids = new ArrayList<>();if (letterList != null) {for (Message message : letterList) {if (hostHolder.getUser().getId() == message.getToId() && message.getStatus() == 0) {ids.add(message.getId());}}}return ids;}@RequestMapping(path = "/letter/send", method = RequestMethod.POST)@ResponseBodypublic String sendLetter(String toName, String content) {User target = userService.findUserByName(toName);if (target == null) {return CommunityUtil.getJSONString(1, "目标用户不存在!");}Message message = new Message();message.setFromId(hostHolder.getUser().getId());message.setToId(target.getId());if (message.getFromId() < message.getToId()) {message.setConversationId(message.getFromId() + "_" + message.getToId());} else {message.setConversationId(message.getToId() + "_" + message.getFromId());}message.setContent(content);message.setCreateTime(new Date());messageService.addMessage(message);return CommunityUtil.getJSONString(0);}@RequestMapping(path = "/notice/list", method = RequestMethod.GET)public String getNoticeList(Model model) {User user = hostHolder.getUser();//要获取当前用户// 查询评论类通知Message message = messageService.findLatestNotice(user.getId(), TOPIC_COMMENT);//传进来固定的主题Map messageVO = new HashMap<>();if (message != null) {messageVO.put("message", message);//需要把message表中的content字段转化成好读写的格式,还原回JSON格式,还原转义字符String content = HtmlUtils.htmlUnescape(message.getContent());//转化成正常的对象,对象类型是hashmapMap data = JSONObject.parseObject(content, HashMap.class);messageVO.put("user", userService.findUserById((Integer) data.get("userId")));messageVO.put("entityType", data.get("entityType"));messageVO.put("entityId", data.get("entityId"));messageVO.put("postId", data.get("postId"));//评论通知的数量int count = messageService.findNoticeCount(user.getId(), TOPIC_COMMENT);messageVO.put("count", count);//未读的数量int unread = messageService.findNoticeUnreadCount(user.getId(), TOPIC_COMMENT);messageVO.put("unread", unread);}//把messageVO放到模板里面,和另外两类的数据要有所区分,// 取名叫评论类的commentNoticemodel.addAttribute("commentNotice", messageVO);//另外的两类通知逻辑一样,参数页类似// 查询点赞类通知message = messageService.findLatestNotice(user.getId(), TOPIC_LIKE);messageVO = new HashMap<>();if (message != null) {messageVO.put("message", message);String content = HtmlUtils.htmlUnescape(message.getContent());Map data = JSONObject.parseObject(content, HashMap.class);messageVO.put("user", userService.findUserById((Integer) data.get("userId")));messageVO.put("entityType", data.get("entityType"));messageVO.put("entityId", data.get("entityId"));messageVO.put("postId", data.get("postId"));int count = messageService.findNoticeCount(user.getId(), TOPIC_LIKE);messageVO.put("count", count);int unread = messageService.findNoticeUnreadCount(user.getId(), TOPIC_LIKE);messageVO.put("unread", unread);}model.addAttribute("likeNotice", messageVO);// 查询关注类通知//关注类的通知,不需要帖子ID,显示的是关注者这个用户message = messageService.findLatestNotice(user.getId(), TOPIC_FOLLOW);messageVO = new HashMap<>();if (message != null) {messageVO.put("message", message);String content = HtmlUtils.htmlUnescape(message.getContent());Map data = JSONObject.parseObject(content, HashMap.class);messageVO.put("user", userService.findUserById((Integer) data.get("userId")));messageVO.put("entityType", data.get("entityType"));messageVO.put("entityId", data.get("entityId"));int count = messageService.findNoticeCount(user.getId(), TOPIC_FOLLOW);messageVO.put("count", count);int unread = messageService.findNoticeUnreadCount(user.getId(), TOPIC_FOLLOW);messageVO.put("unread", unread);}model.addAttribute("followNotice", messageVO);// 查询未读消息数量(总的数量,分两大类,一个是私信的,一个是通知类的消息)int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);model.addAttribute("letterUnreadCount", letterUnreadCount);int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);model.addAttribute("noticeUnreadCount", noticeUnreadCount);//所有主题的维度数量return "/site/notice";}@RequestMapping(path = "/notice/detail/{topic}", method = RequestMethod.GET)public String getNoticeDetail(@PathVariable("topic") String topic, Page page, Model model) {User user = hostHolder.getUser();page.setLimit(5);page.setPath("/notice/detail/" + topic);page.setRows(messageService.findNoticeCount(user.getId(), topic));List noticeList = messageService.findNotices(user.getId(), topic, page.getOffset(), page.getLimit());List> noticeVoList = new ArrayList<>();if (noticeList != null) {for (Message notice : noticeList) {Map map = new HashMap<>();// 通知map.put("notice", notice);// 内容String content = HtmlUtils.htmlUnescape(notice.getContent());Map data = JSONObject.parseObject(content, HashMap.class);map.put("user", userService.findUserById((Integer) data.get("userId")));map.put("entityType", data.get("entityType"));map.put("entityId", data.get("entityId"));map.put("postId", data.get("postId"));// 通知作者map.put("fromUser", userService.findUserById(notice.getFromId()));noticeVoList.add(map);}}model.addAttribute("notices", noticeVoList);// 设置已读List ids = getLetterIds(noticeList);if (!ids.isEmpty()) {messageService.readMessage(ids);}return "/site/notice-detail";}}

在这里插入图片描述
根据页面设置,查看letter.html

在这里插入图片描述
修改notice.html



牛客网-通知

通知详情

MassageMapper.java

// 查询某个主题所包含的通知列表List selectNotices(int userId, String topic, int offset, int limit);

massage-mapper.xml

 

massageService.java

  public List findNotices(int userId, String topic, int offset, int limit) {return messageMapper.selectNotices(userId, topic, offset, limit);}

MessageController.java

 //通知详情,需要传递主题变量@RequestMapping(path = "/notice/detail/{topic}", method = RequestMethod.GET)public String getNoticeDetail(@PathVariable("topic") String topic, Page page, Model model) {User user = hostHolder.getUser();//当前用户page.setLimit(5);page.setPath("/notice/detail/" + topic);page.setRows(messageService.findNoticeCount(user.getId(), topic));List noticeList = messageService.findNotices(user.getId(), topic, page.getOffset(), page.getLimit());//注意几个列表的包含关系List> noticeVoList = new ArrayList<>();if (noticeList != null) {for (Message notice : noticeList) {Map map = new HashMap<>();// 通知map.put("notice", notice);// 内容String content = HtmlUtils.htmlUnescape(notice.getContent());Map data = JSONObject.parseObject(content, HashMap.class);map.put("user", userService.findUserById((Integer) data.get("userId")));map.put("entityType", data.get("entityType"));map.put("entityId", data.get("entityId"));map.put("postId", data.get("postId"));// 通知作者map.put("fromUser", userService.findUserById(notice.getFromId()));noticeVoList.add(map);}}model.addAttribute("notices", noticeVoList);// 设置已读//把一系列的通知消息设置成已读List ids = getLetterIds(noticeList);if (!ids.isEmpty()) {messageService.readMessage(ids);}return "/site/notice-detail";}

notice.html
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

最后处理详情页

notice-detail.html



牛客网-通知详情

系统通知
  • 落基山脉下的闲人2019-04-25 15:49:32
    用户nowcoder评论了你的帖子,点击查看 !用户nowcoder点赞了你的帖子,点击查看 !用户nowcoder关注了你,点击查看 !

在这里插入图片描述

消息总数(私信数+系统消息数)

在这里插入图片描述
用拦截器,因为每个请求都用到了,都需要获取消息总数。
在controller之后,模板之前拦截。

MessageInterceptor.java

package com.nowcoder.community.controller.interceptor;import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.MessageService;
import com.nowcoder.community.util.HostHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;@Component
public class MessageInterceptor implements HandlerInterceptor {@Autowiredprivate HostHolder hostHolder;//获取当前用户@Autowiredprivate MessageService messageService;//消息数量查询需要用到//在controller之后,模板之前拦截@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {User user = hostHolder.getUser();if (user != null && modelAndView != null) {//用户是否已经登录,登录了就可以继续处理int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);int noticeUnreadCount = messageService.findNoticeUnreadCount(user.getId(), null);//给页面传数据即可modelAndView.addObject("allUnreadCount", letterUnreadCount + noticeUnreadCount);}}
}

对拦截器进行配置
在这里插入图片描述

registry.addInterceptor(messageInterceptor).excludePathPatterns("/**/*.css", "/**/*.js", "/**/*.png", "/**/*.jpg", "/**/*.jpeg");对与所有静态资源和动态请求都要拦截

消息的显示是在首页页面:index.html
在这里插入图片描述

相关内容

热门资讯

监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
Fluent中创建监测点 1 概述某些仿真问题,需要创建监测点,用于获取空间定点的数据࿰...
educoder数据结构与算法...                                                   ...
MySQL下载和安装(Wind... 前言:刚换了一台电脑,里面所有东西都需要重新配置,习惯了所...
MFC文件操作  MFC提供了一个文件操作的基类CFile,这个类提供了一个没有缓存的二进制格式的磁盘...
有效的括号 一、题目 给定一个只包括 '(',')','{','}'...
【Ctfer训练计划】——(三... 作者名:Demo不是emo  主页面链接:主页传送门 创作初心ÿ...