1. AJAX
- Asynchronous JavaScript and XML
- 异步的 JavaScript 与 XML 不是一门新技术,而是一个新术语
- 使用 AJAX,网页能够将增量更新呈现在页面上,而不需要刷新整个页面
- 虽然 X 代表 XML,但是目前 JSON 的使用比 XML 更加普遍
2. 功能描述
- 使用 jQuery 发送AJAX请求
- 采用AJAX请求,实现发布帖子的功能
用户点击【发布帖子】按钮后,页面出现一个弹窗,此时后面的页面并没有刷新。
点击【发布帖子】按钮后,publishBtn 按钮会执行 index.js
中的 publish()
方法,跳转到:CONTEXT_PATH + “/discuss/add”;会执行控制器类 DiscussPostController
的 addDiscussPost()
方法。里面调用Service: discussPostService
,该service又调用了 discussPostMapper
,通过其对应的 SQL 语句将帖子内容插进 discuss_post
表中。
3. 开发流程
- 工具类:编写多个(重载)JSONString 相关的方法
- 数据库交互:在 xxxmapper.xml 文件中编写对应的 SQL 语句,并在 Dao 层的接口中声明 CRUD 方法
- 核心业务逻辑:在 Service 层中编写,由该层调用 Dao 层的方法实现对数据层的操作
- 视图层:控制器 + 页面
4. 引入AJAX依赖
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>fastjson</artifactId>
- <version>1.2.58</version>
- </dependency>
5. Util
util/CommunityUtil.java
在用户登录之前,不显示【发布帖子】按钮;
在用户登录之后,才显示【发布帖子】按钮,可以进行相关操作。
- //得到JSON格式的字符串
- //输入为:编号、提示、业务数据
- 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();
- }
- //得到JSON格式的字符串(重载1:无业务数据)
- public static String getJSONString(int code, String msg){
- return getJSONString(code, msg, null);
- }
- //得到JSON格式的字符串(重载2:无提示、业务数据)
- public static String getJSONString(int code){
- return getJSONString(code, null, null);
- }
6. Mapper
dao/DiscussPostMapper.java
添加了 insertDiscussPost()
方法,功能为插入帖子
- package com.nowcoder.community.dao;
- import com.nowcoder.community.entity.DiscussPost;
- import org.apache.ibatis.annotations.Mapper;
- import org.apache.ibatis.annotations.Param;
- import java.util.List;
- @Mapper
- public interface DiscussPostMapper {
- List<DiscussPost> selectDiscussPosts(int userId, int offset, int limit);
- // @Param注解用于给参数取别名
- // 如果只有一个参数,并且在<if>里使用,则必须加别名
- int selectDiscussPostRows(@Param("userId") int userId);
- int insertDiscussPost(DiscussPost discussPost);
- }
mapper/discusspost-mapper.xml
编写对应的 SQL 语句
- <insert id="insertDiscussPost" parameterType="DiscussPost">
- insert into discuss_post(<include refid="insertFields"></include>)
- values (#{userId},#{title},#{content},#{type},#{status},#{createTime},#{commentCount},#{score})
- </insert>
7. Service
service/DiscussPostService.java
编写 addDiscussPost()
,同时注入过滤器
- package com.nowcoder.community.service;
- import com.nowcoder.community.dao.DiscussPostMapper;
- import com.nowcoder.community.entity.DiscussPost;
- import com.nowcoder.community.util.SensitiveFilter;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- import org.springframework.web.util.HtmlUtils;
- import java.util.List;
- @Service
- public class DiscussPostService {
- @Autowired
- private DiscussPostMapper discussPostMapper;
- @Autowired
- private SensitiveFilter sensitiveFilter;
- public List<DiscussPost> findDiscussPosts(int userId, int offset, int limit) {
- return discussPostMapper.selectDiscussPosts(userId, offset, limit);
- }
- public int findDiscussPostRows(int userId) {
- return discussPostMapper.selectDiscussPostRows(userId);
- }
- 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);
- }
- }
8. Controller
- package com.nowcoder.mycommunity.controller;
- import com.nowcoder.mycommunity.entity.DiscussPost;
- import com.nowcoder.mycommunity.entity.User;
- import com.nowcoder.mycommunity.service.DiscussPostService;
- import com.nowcoder.mycommunity.util.CommunityUtil;
- import com.nowcoder.mycommunity.util.HostHolder;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.ResponseBody;
- import java.util.Date;
- //处理所有与发帖相关的请求
- @Controller
- @RequestMapping("/discuss")
- public class DiscussPostController {
- @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){
- // 403表示没有权限
- 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, "发布成功");
- }
- }
9. JavaScript
index.js
在 js 文件中编写【发布按钮】对应的函数 publish()
- $(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");
- // 2秒后,自动隐藏提示框
- setTimeout(function(){
- $("#hintModal").modal("hide");
- // 刷新页面
- if(data.code == 0) {
- window.location.reload();
- }
- }, 2000);
- }
- );
- }
到此这篇关于SpringBoot采用AJAX实现异步发布帖子详解的文章就介绍到这了,更多相关SpringBoot AJAX内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!