# 发送私信
---
## DAO
```java
/**
* 新增一条私信
* @param message
* @return
*/
int insertMessage(Message message);
```
```xml
insert into message()
values(#{fromId}, #{toId}, #{conversationId}, #{content}, #{status}, #{createTime})
```
## Service
```java
// 添加一条私信
public int addMessage(Message message) {
// 转义 HTML 标签
message.setContent(HtmlUtils.htmlEscape(message.getContent()));
// 过滤敏感词
message.setContent(sensitiveFilter.filter(message.getContent()));
return messageMapper.insertMessage(message);
}
```
## Controller
```java
/**
* 发送私信
* @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);
}
```
## 前端
```html
发私信
```
对应的 `letter.js` 文件:
```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();
}
```