发送私信,填写发送信息,点击发送,以异步方式发送给服务器,之后,服务器返回提示结果。
MessageMapper.java(接口)
// 新增消息
int insertMessage(Message message);
// 修改消息的状态
int updateStatus(List<Integer> ids, int status);
message-mapper.xml中实现该方法
<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>
mybatis允许的格式
将id 拼进去,以“,”隔开,修改状态是对多个id的修改,因为在前端页面上显示的多条私信的多条信息。
MessageService.java
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);
}
先在UserService中加入findUserByName(String Name);方法
public User findUserByName(String username) {
return userMapper.selectByName(username);
}
MessageController.java中加方法
@RequestMapping(path = "/letter/send", method = RequestMethod.POST)
@ResponseBody//异步请求
public String sendLetter(String toName, String content) {
User target = userService.findUserByName(toName);
if (target == null) {//判断用户不存在的情况,则不往下运行
return CommunityUtil.getJSONString(1, "目标用户不存在!");//1代表执行错误
}
Message message = new Message();//构造要插入的对象
message.setFromId(hostHolder.getUser().getId());//从当前的用户中去取
message.setToId(target.getId());
if (message.getFromId() < message.getToId()) {//会话id,小的在前,大的在后
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);//没有报错,给页面返回一个状态0,若报错,将来统一处理
}
$(function(){
$("#sendBtn").click(send_letter);
$(".close").click(delete_msg);
});
function send_letter() {
$("#sendModal").modal("hide");
var toName = $("#recipient-name").val();//id选择器
var content = $("#message-text").val();//id选择器
$.post(//异步发post请求
CONTEXT_PATH + "/letter/send",
{"toName":toName,"content":content},
function(data) {//处理 服务端返回的结果
data = $.parseJSON(data);//转化成JSON对象
if(data.code == 0) {//对返回的结果判断
$("#hintBody").text("发送成功!");//通过id获取提示框
} else {
$("#hintBody").text(data.msg);//通过id获取提示框(失败)
}
$("#hintModal").modal("show");//把提示框显示,过两秒隐藏,然后刷新,重载当前页面
setTimeout(function(){
$("#hintModal").modal("hide");
location.reload();
}, 2000);
}
);
}
function delete_msg() {
// TODO 删除数据
$(this).parents(".media").remove();
}
再打开私信详情页面discuss-detail.html,处理发送私信时,自动将target的名字填入
重新启动程序,查看结果
package com.nowcoder.community.controller;
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.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 java.util.*;
@Controller
public class MessageController {
@Autowired
private MessageService messageService;
@Autowired
private HostHolder hostHolder;
@Autowired
private 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<Message> conversationList = messageService.findConversations(
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.findLetterCount(message.getConversationId()));//获取会话中的私信数目
map.put("unreadCount", messageService.findLetterUnreadCount(user.getId(), message.getConversationId()));
int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();//与当前用户相反的头像,可能是from,可能是to;这个地方是与页面的逻辑相对应的
map.put("target", userService.findUserById(targetId));//target对象就得到了
conversations.add(map);
}
}
model.addAttribute("conversations", conversations);//得到数据后传给model模板
// 查询未读消息数量 查整个用户所有的未读消息数量
int letterUnreadCount = messageService.findLetterUnreadCount(user.getId(), null);
model.addAttribute("letterUnreadCount", letterUnreadCount);
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<Message> letterList = messageService.findLetters(conversationId, page.getOffset(), page.getLimit());
List<Map<String, Object>> letters = new ArrayList<>();//当前用户的[from用户]发送的私信
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));
// 设置已读
List<Integer> ids = getLetterIds(letterList);
if (!ids.isEmpty()) {
messageService.readMessage(ids);
}
return "/site/letter-detail";//返回模板
}
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;
}
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);
}
}
@RequestMapping(path = "/letter/send", method = RequestMethod.POST)
@ResponseBody//异步请求
public String sendLetter(String toName, String content) {
User target = userService.findUserByName(toName);
if (target == null) {//判断用户不存在的情况,则不往下运行
return CommunityUtil.getJSONString(1, "目标用户不存在!");//1代表执行错误
}
Message message = new Message();//构造要插入的对象
message.setFromId(hostHolder.getUser().getId());//从当前的用户中去取
message.setToId(target.getId());
if (message.getFromId() < message.getToId()) {//会话id,小的在前,大的在后
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);//没有报错,给页面返回一个状态0,若报错,将来统一处理
}
}