问答平台(3),发布帖子

AJAX

  • Asynchronous JavaScript and XML
  • 异步的JavaScript与XML,不是一门新技术,只是一个新的术语。
  • 使用AJAX,网页能够将增量更新呈现在页面上,而不需要刷新整个页面。
  • 虽然X代表XML,但目前JSON的使用比XML更加普遍。

封装 Json 工具

  • 使用阿里的fastjson,引入依赖。
    1
    2
    3
    4
    5
    <dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.58</version>
    </dependency>
  • 工具类
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    // CommunityUtil.java
    public static String getJSONString(int code, String msg, Map<String, Object> map) {
    JSONObject json = new JSONObject();
    json.put("code", code);
    json.put("msg", msg);
    if (map != null) {
    for (String key : map.keySet()) {
    json.put(key, map.get(key));
    }
    }
    return json.toJSONString();
    }

    public static String getJSONString(int code, String msg) {
    return getJSONString(code, msg, null);
    }

    public static String getJSONString(int code) {
    return getJSONString(code, null, null);
    }

AJAX 示例

  • 使用jQuery发送AJAX请求。

表现层

1
2
3
4
5
6
7
8
9
// AlphaController.java
// ajax示例
@RequestMapping(path = "/ajax", method = RequestMethod.POST)
@ResponseBody
public String testAjax(String name, int age) {
System.out.println(name);
System.out.println(age);
return CommunityUtil.getJSONString(0, "操作成功!");
}

页面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!-- ajax-demo.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax</title>
</head>
<body>
<p>
<input type="button" value="发送" onclick="send();">
</p>

<script src="/js/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
<script>
function send() {
$.post(
"/community/alpha/ajax",
{"name": "张三", "age": 23},
function (data) {
console.log(typeof (data));
console.log(data);

data = $.parseJSON(data);
console.log(typeof (data));
console.log(data.code);
console.log(data.msg);
}
);
}
</script>
</body>
</html>

实战

  • 采用 AJAX 请求,实现发布帖子的功能。

数据访问层

1
2
// DiscussPostMapper.java
int insertDiscussPost(DiscussPost discussPost);
  • discusspost-mapper.xml 里写sql
    1
    2
    3
    4
    5
    6
    7
    <sql id="insertFields">
    user_id, title, content, type, status, create_time, comment_count, score
    </sql>
    <insert id="insertDiscussPost" parameterType="DiscussPost" keyProperty="id">
    insert into discuss_post(<include refid="insertFields"></include>)
    values(#{userId},#{title},#{content},#{type},#{status},#{createTime},#{commentCount},#{score})
    </insert>

业务层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// DiscussPostService.java
private static final Logger logger = LoggerFactory.getLogger(DiscussPostService.class);

@Autowired
private DiscussPostMapper discussPostMapper;

@Autowired
private SensitiveFilter sensitiveFilter;

public int addDiscussPost(DiscussPost post) {
if (post == null) {
throw new IllegalArgumentException("参数不能为空!");
}

// 转义HTML标签
post.setTitle(HtmlUtils.htmlEscape(post.getTitle()));
post.setContent(HtmlUtils.htmlEscape(post.getContent()));
// 过滤敏感词
post.setTitle(sensitiveFilter.filter(post.getTitle()));
post.setContent(sensitiveFilter.filter(post.getContent()));

return discussPostMapper.insertDiscussPost(post);
}

表现层

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// DiscussPostController.java
@Controller
@RequestMapping("/discuss")
public class DiscussPostController implements CommunityConstant {

@Autowired
private DiscussPostService discussPostService;

@Autowired
private HostHolder hostHolder;

@RequestMapping(path = "/add", method = RequestMethod.POST)
@ResponseBody
public String addDiscussPost(String title, String content) {
User user = hostHolder.getUser();
if (user == null) {
return CommunityUtil.getJSONString(403, "还没有登录!");
}

DiscussPost post = new DiscussPost();
post.setUserId(user.getId());
post.setTitle(title);
post.setContent(content);
post.setCreateTime(new Date());
discussPostService.addDiscussPost(post);

// 报错的情况,将来统一处理
return CommunityUtil.getJSONString(0, "发布成功!");
}
}

页面

1
2
3
4
5
6
7
<!-- index.html -->
<!-- 内容 -->
<button type="button" class="btn btn-primary btn-sm position-absolute rt-0" data-toggle="modal"
data-target="#publishModal" th:if="${loginUser!=null}">我要发布
</button>
<!-- 弹出框 -->
<!-- 提示框 -->
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// index.js
$(function () {
$("#publishBtn").click(publish);
});

function publish() {
$("#publishModal").modal("hide");

// 获取标题和内容
var title = $("#recipient-name").val();
var content = $("#message-text").val();
// 发送异步请求(POST)
$.post(
CONTEXT_PATH + "/discuss/add",
{"title": title, "content": content},
function (data) {
data = $.parseJSON(data);
// 在提示框中显示返回消息
$("#hintBody").text(data.msg);
// 显示提示框
$("#hintModal").modal("show");
// 2s后,自动隐藏提示框
setTimeout(function () {
$("#hintModal").modal("hide");
// 刷新页面
if (data.code == 0) {
window.location.reload();
}
}, 2000);
}
);
}

参考资料


问答平台(3),发布帖子
https://lcf163.github.io/2020/05/08/问答平台(3),发布帖子/
作者
乘风的小站
发布于
2020年5月8日
许可协议