牛客网项目---4.3.显示系统消息

本文介绍了如何通过Spring Boot和MyBatis实现消息通知的管理,包括私信、评论、点赞和关注的通知列表、详情展示、未读消息计数,以及对特定主题的通知筛选。通过拦截器实时更新整体消息数,提升用户体验。
摘要由CSDN通过智能技术生成

显示系统通知

通知列表:

——显示评论、点赞、关注三种类型的通知

通知详情 :

——分页显示某一类主题所包含的通知

未读消息 :

——在页面头部显示所有的未读消息数量

1.MessageMapper:

import com.nowcoder.community.entity.Message;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface MessageMapper {

    //查询当前用户的会话列表,针对每个用户只返回一条最新的私信
    List<Message> selectConversations(int userId,int offset,int limit);

    //查询当前用户的会话数量
    int selectConversationCount(int userId);

    //查询某个会话所包含的私信列表
    List<Message> selectLetters(String conversationId,int offset,int limit);

    //查询某个会话所包含的私信数量
    int selectLetterCount(String conversationId);

    //查询未读私信数量
    int selectLetterUnreadCount(int userId,String conversationId);

    //新增消息
    int insertMessage(Message message);

    //修改消息状态
    int updateStatus(List<Integer> ids,int status);

    //查询某个主题下最新的通知
    Message selectLateNotice(int userId,String topic);

    //查询某个主题下所包含的通知数量
    int selectNoticeCount(int userId,String topic);

    //查询未读的通知数量
    int selectNoticeUnreadCount(int userId,String topic);

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

2.MessageMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.nowcoder.community.mapper.MessageMapper">

    <select id="selectConversations" resultType="Message">
        select *
        from message
        where id in (
          select max(id) from message
          where status != 2
          and from_id != 1
          and (from_id = #{userId} or to_id = #{userId})
          group by conversation_id
        )
        order by id desc
        limit #{offset},#{limit}
    </select>

    <select id="selectConversationCount" resultType="int">
        select count(m.maxid) from (
             select max(id) as maxid from message
             where status!=2
             and from_id!=1
             and (from_id=#{userId} or to_id=#{userId})
             group by conversation_id
        ) as m
    </select>

    <select id="selectLetters" resultType="Message">
        select * from message where status!=2 and from_id!=1 and conversation_id=#{conversationId} order by id desc limit #{offset},#{limit};
    </select>

    <select id="selectLetterCount" resultType="int">
        select count(id) from message where status!=2 and from_id!=1 and conversation_id=#{conversationId};
    </select>

    <select id="selectLetterUnreadCount" resultType="int">
        select count(id) from message where status=0 and from_id!=1 and to_id=#{userId}
        <if test="conversationId!=null">
            and conversation_id=#{conversationId}
        </if>
    </select>

    <insert id="insertMessage" parameterType="Message" keyProperty="id">
        insert into message(from_id, to_id, conversation_id, content, status, create_time) VALUES (#{fromId},#{toId},#{conversationId},#{content},#{status},#{createTime});
    </insert>

    <update id="updateStatus" parameterType="int">
        update message set status=#{status} where id in
        <foreach collection="ids" item="id" open="(" separator="," close=")">
            #{id}
        </foreach>
    </update>

    <select id="selectLateNotice" resultType="Message">
        select *
        from message
        where id in (
            select max(id) from message
            where status!=2
            and from_id=1
            and to_id=#{userId}
            and conversation_id=#{topic}
            )
    </select>

    <select id="selectNoticeCount" resultType="int">
        select count(id) from message
        where status!=2 and from_id=1 and to_id=#{userId} and conversation_id=#{topic}
    </select>

    <select id="selectNoticeUnreadCount" resultType="int">
        select count(id) from message
        where status = 0
        and from_id = 1
        and to_id = #{userId}
        <if test="topic!=null">
            and conversation_id = #{topic}
        </if>
    </select>

    <select id="selectNotices" resultType="Message">
        select * from message where status!=2 and from_id=1 and to_id=#{userId} and conversation_id=#{topic} order by create_time desc limit #{offset},#{limit};
    </select>
</mapper>

3.MessageService:

import com.nowcoder.community.entity.Message;
import com.nowcoder.community.mapper.MessageMapper;
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 MessageServiceImpl implements MessageService{

    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;

    @Override
    public List<Message> selectConversations(int userId, int offset, int limit) {
        return messageMapper.selectConversations(userId, offset, limit);
    }

    @Override
    public int selectConversationCount(int userId) {
        return messageMapper.selectConversationCount(userId);
    }

    @Override
    public List<Message> selectLetters(String conversationId, int offset, int limit) {
        return messageMapper.selectLetters(conversationId, offset, limit);
    }

    @Override
    public int selectLetterCount(String conversationId) {
        return messageMapper.selectLetterCount(conversationId);
    }

    @Override
    public int selectLetterUnreadCount(int userId, String conversationId) {
        return messageMapper.selectLetterUnreadCount(userId, conversationId);
    }

    @Override
    public int insertMessage(Message message) {
        return messageMapper.insertMessage(message);
    }

    @Override
    public int updateStatus(List<Integer> ids, int status) {
        return messageMapper.updateStatus(ids, status);
    }

    @Override
    public Message selectLateNotice(int userId, String topic) {
        return messageMapper.selectLateNotice(userId, topic);
    }

    @Override
    public int selectNoticeCount(int userId, String topic) {
        return messageMapper.selectNoticeCount(userId, topic);
    }

    @Override
    public int selectNoticeUnreadCount(int userId, String topic) {
        return messageMapper.selectNoticeUnreadCount(userId, topic);
    }

    @Override
    public List<Message> selectNotices(int userId, String topic, int offset, int limit) {
        return messageMapper.selectNotices(userId, topic, offset, limit);
    }

    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<Integer> ids){
        return messageMapper.updateStatus(ids,1);
    }
}

4.MessageController:

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.MessageServiceImpl;
import com.nowcoder.community.service.UserServiceImpl;
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.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

@Controller
public class MessageController implements CommunityConstant {

    @Autowired
    private MessageServiceImpl messageService;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private HostHolder hostHolder;

    @GetMapping("/letter/list")
    public String getLetterList(Model model, Page page){
        User user = hostHolder.getUser();
        //分页信息
        page.setLimit(5);
        page.setPath("/letter/list");
        page.setRows(messageService.selectConversationCount(user.getId()));

        //会话列表
        List<Message> conversationList = messageService.selectConversations(user.getId(), page.getOffset(), page.getLimit());
        List<Map<String,Object>> conversations=new ArrayList<>();
        if (conversationList!=null){
            for (Message message : conversationList) {
                Map<String,Object> map=new HashMap<>();
                map.put("conversation",message);
                map.put("letterCount",messageService.selectLetterCount(message.getConversationId()));
                map.put("unreadCount",messageService.selectLetterUnreadCount(user.getId(), message.getConversationId()));
                int target= user.getId()== message.getFromId() ? message.getToId() : message.getFromId();
                map.put("target",userService.selectById(target));

                conversations.add(map);
            }
        }
        model.addAttribute("conversations",conversations);

        //查询未读消息数量
        int letterUnreadCount = messageService.selectLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount",letterUnreadCount);
        int noticeUnreadCount = messageService.selectNoticeUnreadCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);

        return "/site/letter";
    }

    @GetMapping("/letter/detail/{conversationId}")
    public String getLetterDetail(Model model,@PathVariable("conversationId") String conversationId,Page page){
        User user = hostHolder.getUser();

        //分页信息
        page.setPath("/letter/detail/"+conversationId);
        page.setLimit(5);
        page.setRows(messageService.selectLetterCount(conversationId));

        //私信列表
        List<Message> lettersList = messageService.selectLetters(conversationId, page.getOffset(), page.getLimit());
        List<Map<String,Object>> letters=new ArrayList<>();
        if (lettersList!=null){
            for (Message letter : lettersList) {
                Map<String,Object> map=new HashMap<>();
                map.put("letter",letter);
                map.put("fromUser",userService.selectById(letter.getFromId()));

                letters.add(map);
            }
        }
        model.addAttribute("letters",letters);

        //私信目标
        model.addAttribute("target",getLetterTarget(conversationId));

        //设置已读
        List<Integer> ids = getLetterIds(lettersList);
        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.selectById(id1);
        }
        else {
            return userService.selectById(id0);
        }
    }

    //获取未读消息的id
    private List<Integer> getLetterIds(List<Message> letterList){
        List<Integer> 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;
    }

    @PostMapping("/letter/send")
    @ResponseBody
    public String sendLetter(String toName,String content){
        User target = userService.selectByName(toName);
        if (target==null){
            return CommunityUtil.getJSONString(1,"目标用户不存在!");
        }

        Message message = new Message();
        message.setContent(content);
        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.setCreateTime(new Date());

        messageService.addMessage(message);

        return CommunityUtil.getJSONString(0);
    }

    @GetMapping("/notice/list")
    public String getNoticeList(Model model){
        User user = hostHolder.getUser();

        //查询评论类通知
        Message message = messageService.selectLateNotice(user.getId(), TOPIC_COMMENT);
        if (message!=null){
            Map<String,Object> messageVo=new HashMap<>();

            messageVo.put("message",message);

            String content= HtmlUtils.htmlUnescape(message.getContent());
            Map<String,Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVo.put("user",userService.selectById((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.selectNoticeCount(user.getId(), TOPIC_COMMENT);
            messageVo.put("count",count);

            int unreadCount = messageService.selectNoticeUnreadCount(user.getId(), TOPIC_COMMENT);
            messageVo.put("unread",unreadCount);

            model.addAttribute("commentNotice",messageVo);
        }

        //查询点赞类通知
        message = messageService.selectLateNotice(user.getId(), TOPIC_LIKE);
        if (message!=null){
            Map<String,Object> messageVo=new HashMap<>();

            String content=HtmlUtils.htmlUnescape(message.getContent());
            Map<String,Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVo.put("user",userService.selectById((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.selectNoticeCount(user.getId(), TOPIC_LIKE);
            messageVo.put("count",count);

            int unreadCount = messageService.selectNoticeUnreadCount(user.getId(), TOPIC_LIKE);
            messageVo.put("unread",unreadCount);

            model.addAttribute("likeNotice",messageVo);
        }

        //查询关注类通知
        message=messageService.selectLateNotice(user.getId(), TOPIC_FOLLOW);
        if (message!=null){
            Map<String,Object> messageVo=new HashMap<>();

            messageVo.put("message",message);

            String content=HtmlUtils.htmlUnescape(message.getContent());
            Map<String,Object> data = JSONObject.parseObject(content, HashMap.class);

            messageVo.put("user",userService.selectById((Integer) data.get("userId")));
            messageVo.put("entityType",data.get("entityType"));
            messageVo.put("entityId",data.get("entityId"));

            int count = messageService.selectNoticeCount(user.getId(), TOPIC_FOLLOW);
            messageVo.put("count",count);

            int unreadCount = messageService.selectNoticeUnreadCount(user.getId(), TOPIC_FOLLOW);
            messageVo.put("unread",unreadCount);

            model.addAttribute("followNotice",messageVo);
        }

        //查询未读消息数量
        int letterUnreadCount = messageService.selectLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount",letterUnreadCount);
        int noticeUnreadCount = messageService.selectNoticeUnreadCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount",noticeUnreadCount);

        return "/site/notice";
    }

    @GetMapping("/notice/detail/{topic}")
    public String getNoticeDetail(@PathVariable("topic") String topic,Page page,Model model){
        User user = hostHolder.getUser();

        page.setPath("/notice/detail/"+topic);
        page.setLimit(5);
        page.setRows(messageService.selectNoticeCount(user.getId(), topic));

        List<Message> noticeList = messageService.selectNotices(user.getId(), topic, page.getOffset(), page.getLimit());
        List<Map<String,Object>> noticeVoList=new ArrayList<>();
        if (noticeList!=null){
            for (Message notice : noticeList) {
                Map<String,Object> map=new HashMap<>();
                //通知
                map.put("notice",notice);

                //内容
                String content=HtmlUtils.htmlUnescape(notice.getContent());
                Map<String,Object> data = JSONObject.parseObject(content, HashMap.class);
                map.put("user",userService.selectById((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.selectById(notice.getFromId()));

                noticeVoList.add(map);
            }
        }
        model.addAttribute("notices",noticeVoList);

        //设置已读
        List<Integer> ids = getLetterIds(noticeList);
        if (!ids.isEmpty()){
            messageService.readMessage(ids);
        }

        return "/site/notice-detail";
    }
}

5.letter.html:

<div class="position-relative">
		<!-- 选项 -->
		<ul class="nav nav-tabs mb-3">
				<li class="nav-item">
						<a class="nav-link position-relative active" th:href="@{/letter/list}">
								朋友私信<span class="badge badge-danger" th:text="${letterUnreadCount}" th:if="${letterUnreadCount!=0}">3</span>
						</a>
				</li>
				<li class="nav-item">
						<a class="nav-link position-relative" th:href="@{/notice/list}">
							系统通知<span class="badge badge-danger" th:text="${noticeUnreadCount}" th:if="${noticeUnreadCount!=0}">27</span>
						</a>
				</li>
		</ul>
	<button type="button" class="btn btn-primary btn-sm position-absolute rt-0" data-toggle="modal" data-target="#sendModal">发私信
    </button>
</div>

6.notice.html:

<!-- 内容 -->
		<div class="main">
			<div class="container">
				<div class="position-relative">
					<!-- 选项 -->
					<ul class="nav nav-tabs mb-3">
						<li class="nav-item">
							<a class="nav-link position-relative" th:href="@{/letter/list}">
								朋友私信<span class="badge badge-danger" th:text="${letterUnreadCount}" th:if="${letterUnreadCount!=0}">3</span>
							</a>
						</li>
						<li class="nav-item">
							<a class="nav-link position-relative active" th:href="@{/notice/list}">
								系统通知<span class="badge badge-danger" th:text="${noticeUnreadCount}" th:if="${noticeUnreadCount!=0}">27</span>
							</a>
						</li>
					</ul>
				</div>	
				
				<!-- 通知列表 -->
				<ul class="list-unstyled">
					<!--评论类通知-->
					<li class="media pb-3 pt-3 mb-3 border-bottom position-relative" th:if="${commentNotice!=null}">
						<span class="badge badge-danger" th:text="${commentNotice.unread!=0?commentNotice.unread:''}">3</span>
						<img src="http://static.nowcoder.com/images/head/reply.png" class="mr-4 user-header" alt="通知图标">
						<div class="media-body">
							<h6 class="mt-0 mb-3">
								<span>评论</span>
								<span class="float-right text-muted font-size-12"
									th:text="${#dates.format(commentNotice.message.createTime,'yyyy-MM-dd HH:mm:ss')}">日期</span>
							</h6>
							<div>
								<a th:href="@{/notice/detail/comment}">
									用户
									<i th:utext="${commentNotice.user.username}">用户名</i>
									评论了你的<b th:text="${commentNotice.entityType==1?'帖子':'回复'}">帖子</b> ...
								</a>
								<ul class="d-inline font-size-12 float-right">
									<li class="d-inline ml-2"><span class="text-primary">共 <i th:text="${commentNotice.count}">3</i> 条会话</span></li>
								</ul>
							</div>
						</div>
					</li>
					<!--点赞类通知-->
					<li class="media pb-3 pt-3 mb-3 border-bottom position-relative" th:if="${likeNotice!=null}">
						<span class="badge badge-danger" th:text="${likeNotice.unread!=0?likeNotice.unread:''}">3</span>
						<img src="http://static.nowcoder.com/images/head/like.png" class="mr-4 user-header" alt="通知图标">
						<div class="media-body">
							<h6 class="mt-0 mb-3">
								<span>赞</span>
								<span class="float-right text-muted font-size-12"
									  th:text="${#dates.format(likeNotice.message.createTime,'yyyy-MM-dd HH:mm:ss')}">日期</span>
							</h6>
							<div>
								<a th:href="@{/notice/detail/like}">
									用户
									<i th:utext="${likeNotice.user.username}">用户名</i>
									点赞了你的<b th:text="${likeNotice.entityType==1?'帖子':'回复'}">帖子</b> ...
								</a>
								<ul class="d-inline font-size-12 float-right">
									<li class="d-inline ml-2"><span class="text-primary">共 <i th:text="${likeNotice.count}">3</i> 条会话</span></li>
								</ul>
							</div>
						</div>
					</li>
					<!--关注类通知-->
					<li class="media pb-3 pt-3 mb-3 border-bottom position-relative" th:if="${followNotice!=null}">
						<span class="badge badge-danger" th:text="${followNotice.unread!=0?followNotice.unread:''}">3</span>
						<img src="http://static.nowcoder.com/images/head/follow.png" class="mr-4 user-header" alt="通知图标">
						<div class="media-body">
							<h6 class="mt-0 mb-3">
								<span>关注</span>
								<span class="float-right text-muted font-size-12"
									  th:text="${#dates.format(followNotice.message.createTime,'yyyy-MM-dd HH:mm:ss')}">2019-04-28 14:13:25</span>
							</h6>
							<div>
								<a th:href="@{/notice/detail/follow}">
									用户
									<i th:utext="${followNotice.user.username}">用户名</i>
									关注了你 ...
								</a>
								<ul class="d-inline font-size-12 float-right">
									<li class="d-inline ml-2"><span class="text-primary">共 <i th:text="${followNotice.count}">3</i> 条会话</span></li>
								</ul>
							</div>
						</div>
					</li>					
				</ul>
			</div>
		</div>

7.notice-detail.html:

<!-- 内容 -->
		<div class="main">
			<div class="container">
				<div class="row">
					<div class="col-8">
						<h6><b class="square"></b> 系统通知</h6>
					</div>
					<div class="col-4 text-right">
						<button type="button" class="btn btn-secondary btn-sm" onclick="back();">返回</button>
					</div>
				</div>
				
				<!-- 通知列表 -->
				<ul class="list-unstyled mt-4">
					<li class="media pb-3 pt-3 mb-2" th:each="map:${notices}">
						<img th:src="${map.fromUser.headerUrl}" class="mr-4 rounded-circle user-header" alt="系统图标">
						<div class="toast show d-lg-block" role="alert" aria-live="assertive" aria-atomic="true">
							<div class="toast-header">
								<strong class="mr-auto" th:utext="${map.fromUser.username}">用户名</strong>
								<small th:text="${#dates.format(map.notice.createTime,'yyyy-MM-dd HH:mm:ss')}">日期</small>
								<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
									<span aria-hidden="true">&times;</span>
								</button>
							</div>
							<div class="toast-body">
								<span th:if="${topic.equals('comment')}">
									用户
									<i th:utext="${map.user.username}">用户名</i>
									评论了你的<b th:text="${map.entityType==1?'帖子':'回复'}">帖子</b>,
									<a class="text-primary" th:href="@{|/discuss/detail/${map.postId}|}">点击查看</a> !
								</span>
								<span th:if="${topic.equals('like')}">
									用户
									<i th:utext="${map.user.username}">用户名</i>
									点赞了你的<b th:text="${map.entityType==1?'帖子':'回复'}">帖子</b>,
									<a class="text-primary" th:href="@{|/discuss/detail/${map.postId}|}">点击查看</a> !
								</span>
								<span th:if="${topic.equals('follow')}">
									用户
									<i th:utext="${map.user.username}">用户名</i>
									关注了你,
									<a class="text-primary" th:href="@{|/user/profile/${map.user.id}|}">点击查看</a> !
								</span>
							</div>
						</div>
					</li>
				</ul>
				<!-- 分页 -->
				<nav class="mt-5" th:replace="index::pagination">
					<ul class="pagination justify-content-center">
						<li class="page-item"><a class="page-link" href="#">首页</a></li>
						<li class="page-item disabled"><a class="page-link" href="#">上一页</a></li>
						<li class="page-item active"><a class="page-link" href="#">1</a></li>
						<li class="page-item"><a class="page-link" href="#">2</a></li>
						<li class="page-item"><a class="page-link" href="#">3</a></li>
						<li class="page-item"><a class="page-link" href="#">4</a></li>
						<li class="page-item"><a class="page-link" href="#">5</a></li>
						<li class="page-item"><a class="page-link" href="#">下一页</a></li>
						<li class="page-item"><a class="page-link" href="#">末页</a></li>
					</ul>
				</nav>
			</div>
		</div>

8.显示整体消息的数量

通过拦截器获取整体消息的数量,进行显示。

MessageInterceptor:

import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.MessageServiceImpl;
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{

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private MessageServiceImpl messageService;


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        User user = hostHolder.getUser();
        if (user!=null&&modelAndView!=null){
            int letterUnreadCount = messageService.selectLetterUnreadCount(user.getId(), null);
            int noticeUnreadCount = messageService.selectNoticeUnreadCount(user.getId(), null);
            modelAndView.addObject("allUnreadCount",letterUnreadCount+noticeUnreadCount);
        }
    }
}

9.配置拦截器:WebMvcConfig

import com.nowcoder.community.interceptor.LoginRequiredInterceptor;
import com.nowcoder.community.interceptor.LoginTicketInterceptor;
import com.nowcoder.community.interceptor.MessageInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private LoginTicketInterceptor loginTicketInterceptor;

    @Autowired
    private LoginRequiredInterceptor loginRequiredInterceptor;

    @Autowired
    private MessageInterceptor messageInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        registry.addInterceptor(loginTicketInterceptor)
                .excludePathPatterns("/**/*.css","/**/*.js","/**/*.jpg","/**/*.png","/**/*.jpeg");

        registry.addInterceptor(loginRequiredInterceptor)
                .excludePathPatterns("/**/*.css","/**/*.js","/**/*.jpg","/**/*.png","/**/*.jpeg");

        registry.addInterceptor(messageInterceptor)
                .excludePathPatterns("/**/*.css","/**/*.js","/**/*.jpg","/**/*.png","/**/*.jpeg");
    }
}

10.index.html:

<li class="nav-item ml-3 btn-group-vertical" th:if="${loginUser!=null}">
	<a class="nav-link position-relative" th:href="@{/letter/list}">消息
    	<span class="badge badge-danger" th:text="${allUnreadCount!=0?allUnreadCount:''}">12</span>
   </a>
</li>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值