2.9 KiB
2.9 KiB
发送私信
DAO
/**
* 新增一条私信
* @param message
* @return
*/
int insertMessage(Message message);
<!--新增一条私信-->
<insert id="insertMessage" parameterType="Message" keyProperty="id">
insert into message(<include refid="insertFields"></include>)
values(#{fromId}, #{toId}, #{conversationId}, #{content}, #{status}, #{createTime})
</insert>
Service
// 添加一条私信
public int addMessage(Message message) {
// 转义 HTML 标签
message.setContent(HtmlUtils.htmlEscape(message.getContent()));
// 过滤敏感词
message.setContent(sensitiveFilter.filter(message.getContent()));
return messageMapper.insertMessage(message);
}
Controller
/**
* 发送私信
* @param toName 收信人 username
* @param content 内容
* @return
*/
@PostMapping("/letter/send")
@ResponseBody
public 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.setStatus(0); // 默认就是 0 未读,可不写
message.setCreateTime(new Date());
messageService.addMessage(message);
return CommunityUtil.getJSONString(0);
}
前端
<h5 id="exampleModalLabel">发私信</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"></button>
<div class="modal-body">
<form>
<input id="recipient-name">
<textarea id="message-text" ></textarea>
</form>
</div>
<div class="modal-footer">
<button id="sendBtn">发送</button>
</div>
对应的 letter.js
文件:
$(function(){
$("#sendBtn").click(send_letter);
$(".close").click(delete_msg);
});
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);
}
)
}
function delete_msg() {
// TODO 删除数据
$(this).parents(".media").remove();
}