测试用户:用户名aaa 密码aaa
- 查询当前用户的会话列表;
- 每个会话只显示一条最新的私信;
- 支持分页显示。
首先看下表结构:
- conversation_id: 用from_id和to_id拼接,小的放前面去(因为两个人的对话应该在一个会话中)
DAO层
- 添加messgge实体类:
public class Message {private int id;private int fromId;private int toId;private String conversationId;private String content;private int status;private Date createTime;public int getId() {return id;}public void setId(int id) {this.id = id;}public int getFromId() {return fromId;}public void setFromId(int fromId) {this.fromId = fromId;}public int getToId() {return toId;}public void setToId(int toId) {this.toId = toId;}public String getConversationId() {return conversationId;}public void setConversationId(String conversationId) {this.conversationId = conversationId;}public String getContent() {return content;}public void setContent(String content) {this.content = content;}public int getStatus() {return status;}public void setStatus(int status) {this.status = status;}public Date getCreateTime() {return createTime;}public void setCreateTime(Date createTime) {this.createTime = createTime;}@Overridepublic String toString() {return "Message{" +"id=" + id +", fromId=" + fromId +", toId=" + toId +", conversationId='" + conversationId + '\'' +", content='" + content + '\'' +", status=" + status +", createTime=" + createTime +'}';}
}
- message-mapper接口
@Mapper
public interface MessageMapper {// 1. 查询当前用户的会话列表,针对每个会话只返回一条最新的私信(分页)List<Message> selectConversations(int userId, int offset, int limit);// 2. 查询当前用户的会话数量int selectConversationCount(int userId);// 3. 查询某个会话所包含的私信列表(分页)List<Message> selectLetters(String conversationId, int offset, int limit);// 4. 查询某个会话所包含的私信数量int selectLetterCount(String conversationId);// 5. 查询未读私信的数量int selectLetterUnreadCount(int userId, String conversationId);
}
- 编写message-mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.nowcoder.community.dao.MessageMapper"><sql id="selectFields">id, from_id, to_id, conversation_id, content, status, create_time</sql><sql id="insertFields">from_id, to_id, conversation_id, content, status, create_time</sql><select id="selectConversations" resultType="Message">select <include refid="selectFields"></include>from messagewhere id in (select max(id) from messagewhere status != 2and from_id != 1and (from_id = #{userId} or to_id = #{userId})group by conversation_id)order by id desclimit #{offset}, #{limit}</select><select id="selectConversationCount" resultType="int">select count(m.maxid) from (select max(id) as maxid from messagewhere status != 2and from_id != 1and (from_id = #{userId} or to_id = #{userId})group by conversation_id) as m</select><select id="selectLetters" resultType="Message">select <include refid="selectFields"></include>from messagewhere status != 2and from_id != 1and conversation_id = #{conversationId}order by id desclimit #{offset}, #{limit}</select><select id="selectLetterCount" resultType="int">select count(id)from messagewhere status != 2and from_id != 1and conversation_id = #{conversationId}</select><select id="selectLetterUnreadCount" resultType="int">select count(id)from messagewhere status = 0and from_id != 1and to_id = #{userId}<if test="conversationId!=null">and conversation_id = #{conversationId}</if></select>
</mapper>
业务层
@Service
public class MessageService {@Autowiredprivate MessageMapper messageMapper;public List<Message> findConversations(int userId, int offset, int limit) {return messageMapper.selectConversations(userId, offset, limit);}public int findConversationCount(int userId) {return messageMapper.selectConversationCount(userId);}public List<Message> 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);}}
Controller层
显示私信列表
创建MessageController:
@Controller
public class MessageController {@Autowiredprivate MessageService messageService;@Autowiredprivate HostHolder hostHolder;@Autowiredprivate UserService userService;// 1. 查询当前用户的会话列表,针对每个会话只返回一条最新的私信(分页)// /letter/list// GET@RequestMapping(path = "/letter/list", method = RequestMethod.GET)public String getLetterList(Model model, Page page) {User user = hostHolder.getUser();// 1. 设置分页信息page.setLimit(5);page.setPath("/letter/list");page.setRows(messageService.findConversationCount(user.getId()));// 2. 查询会话列表List<Message> conversationList = messageService.findConversations(hostHolder.getUser().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.findLetterCount(message.getConversationId()));map.put("unreadCount", messageService.findLetterUnreadCount(user.getId(), message.getConversationId()));//下面的逻辑是:如果当前用户是消息的接收者,那么target就是发送者,反之就是当前用户是发送者,那么target就是接收者int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();map.put("target", userService.findUserById(targetId));conversations.add(map);}}model.addAttribute("conversations", conversations);// 3. 查询未读消息数量,查询的是所有的未读消息数量int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);model.addAttribute("letterUnreadCount", letterUnreadCount);return "/site/letter";}// 2. 查询当前用户的会话详情// /letter/detail/{conversationId}// GETpublic String getLetterDetail() {return "/site/letter-detail";}// 3. 发送私信// /letter/send// POSTpublic String sendLetter() {return "redirect:/letter/list";}
}
显示私信详情
@RequestMapping(path = "/letter/detail/{conversationId}", method = RequestMethod.GET)public String getLetterDetail(@PathVariable("conversationId") String conversationId, Page page, Model model) {// 1. 设置分页信息(之后需要分页的地方都是这个逻辑)page.setLimit(5);page.setPath("/letter/detail/" + conversationId);page.setRows(messageService.findLetterCount(conversationId));//2. 查询私信列表List<Message> letterList = messageService.findLetters(conversationId, page.getOffset(), page.getLimit());//3. 完善用户信息List<Map<String, Object>> letters = new ArrayList<>();if(letterList != null){for(Message message : letterList){Map<String, Object> 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));return "/site/letter-detail";
}
修改模版成动态
显示私信列表
- 首先修改index.html将“消息”链接到/letter/list
<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">12</span></a>
</li>
- 修改letter.html,替换头部到首页的头部
<!-- 头部 --><header class="bg-dark sticky-top" th:replace="index::header">
- 修改朋友私信的头显示未读消息数目
<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>
- 修改私信列表的迭代:
<!-- 私信列表 --><ul class="list-unstyled"><li class="media pb-3 pt-3 mb-3 border-bottom position-relative" th:each="map:${conversations}"><span class="badge badge-danger" th:text="${map.unreadCount}" th:if="${map.unreadCount!=0}">3</span><a href="profile.html"><img th:src="${map.target.headerUrl}" class="mr-4 rounded-circle user-header" alt="用户头像" ></a><div class="media-body"><h6 class="mt-0 mb-3"><span class="text-success" th:utext="${map.target.username}">落基山脉下的闲人</span><span class="float-right text-muted font-size-12" th:text="${#dates.format(map.conversation.createTime,'yyyy-MM-dd HH:mm:ss')}">2019-04-28 14:13:25</span></h6><div><a th:href="@{|/letter/detail/${map.conversation.conversationId}|}" th:utext="${map.conversation.content}">米粉车, 你来吧!</a><ul class="d-inline font-size-12 float-right"><li class="d-inline ml-2"><a href="#" class="text-primary">共<i th:text="${map.letterCount}">5</i>条会话</a></li></ul></div></div></li></ul>
${conversations}是一个在后端代码中设置的模型属性,它包含了一组会话数据。map是迭代过程中的变量,它在每次迭代时都会被设置为当前元素的值。
- 复用之前的分页逻辑:
<!-- 分页 --><nav class="mt-5" th:replace="index::pagination">
显示私信详情
- letter.html链接到详情页面:
<div><a th:href="@{|/letter/detail/${map.conversation.conversationId}|}" th:utext="${map.conversation.content}">米粉车, 你来吧!</a><ul class="d-inline font-size-12 float-right"><li class="d-inline ml-2"><a href="#" class="text-primary">共<i th:text="${map.letterCount}">5</i>条会话</a></li></ul>
</div>
- 修改letter-detail.html
<div class="col-8"><h6><b class="square"></b> 来自 <i class="text-success" th:utext="${target.username}">落基山脉下的闲人</i> 的私信</h6>
</div>
- 设置th:each
<!-- 私信列表 --><ul class="list-unstyled mt-4"><li class="media pb-3 pt-3 mb-2" th:each="map:${letters}">
- 设置返回重定向回去:使用js
<button type="button" class="btn btn-secondary btn-sm" onclick="back();">返回</button>...<script>function back() {location.href = CONTEXT_PATH + "/letter/list";}
</script>
发送私信
数据访问层
// 新增消息
int insertMessage(Message message);// 修改消息的状态(多个未读变成已读)
int updateStatus(List<Integer> ids, int status);
修改mapper的xml:
<sql id="insertFields">from_id, to_id, conversation_id, content, status, create_time
</sql>
...
<insert id="insertMessage" parameterType="Message" keyProperty="id">insert into message(<include refid="insertFields"></include>)values(#{fromId},#{toId},#{conversationId},#{content},#{status},#{createTime})
</insert><update id="updateStatus">update message set status = #{status}where id in<foreach collection="ids" item="id" open="(" separator="," close=")">#{id}</foreach>
</update>
- 语法:
它用于在SQL查询中插入一个动态的列表。在这个例子中,collection=“ids"表示输入参数中应该包含一个名为ids的集合,item=“id"表示在每次迭代时,集合中的当前元素将被赋值给变量id。 open=”(”,separator=",“和close=”)"这些属性用于定义生成的列表的格式。open和close定义了列表的开头和结尾,separator定义了列表中的元素之间的分隔符.
业务层
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);
}
Controller层
异步请求,要用@ResponseBody返回json
@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());//设置会话idif(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);//给页面返回一个状态(0表示成功,1表示失败)return CommunityUtil.getJsonString(0);}
- 这里的findUserByName还没有实现,要在UserService中实现一下:
public User findUserByName(String username) {return userMapper.selectByName(username);}
- 修改使消息可以已读:
...List<Integer> letterIds = getLetterIds(letterList);if(!letterIds.isEmpty()){messageService.readMessage(letterIds);}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;
}
修改letter.html模版
- 修改letter.js接收json:
function send_letter() {$("#sendModal").modal("hide");var toName = $("#recipient-name").val();var content = $("#message-text").val();$.post(CONTEXT_PATH + "/letter/send",{"toName":toName,"content":content},function(data) {data = $.parseJSON(data);if(data.code == 0) {$("#hintBody").text("发送成功!");} else {$("#hintBody").text(data.msg);}$("#hintModal").modal("show");setTimeout(function(){$("#hintModal").modal("hide");location.reload();}, 2000);});
}
- 修改letter-detail.html
<div class="toast-header"><strong class="mr-auto" th:utext="${map.fromUser.username}">落基山脉下的闲人</strong><small th:text="${#dates.format(map.letter.createTime,'yyyy-MM-dd HH:mm:ss')}">2019-04-25 15:49:32</small><button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close"><span aria-hidden="true">×</span></button>
</div>