SpringBoot采用AJAX實現(xiàn)異步發(fā)布帖子詳解
1. AJAX
- Asynchronous JavaScript and XML
- 異步的 JavaScript 與 XML 不是一門新技術(shù),而是一個新術(shù)語
- 使用 AJAX,網(wǎng)頁能夠?qū)⒃隽扛鲁尸F(xiàn)在頁面上,而不需要刷新整個頁面
- 雖然 X 代表 XML,但是目前 JSON 的使用比 XML 更加普遍
2. 功能描述
- 使用 jQuery 發(fā)送AJAX請求
- 采用AJAX請求,實現(xiàn)發(fā)布帖子的功能
用戶點擊【發(fā)布帖子】按鈕后,頁面出現(xiàn)一個彈窗,此時后面的頁面并沒有刷新。
點擊【發(fā)布帖子】按鈕后,publishBtn 按鈕會執(zhí)行 index.js
中的 publish()
方法,跳轉(zhuǎn)到:CONTEXT_PATH + “/discuss/add”;會執(zhí)行控制器類 DiscussPostController
的 addDiscussPost()
方法。里面調(diào)用Service: discussPostService
,該service又調(diào)用了 discussPostMapper
,通過其對應(yīng)的 SQL 語句將帖子內(nèi)容插進 discuss_post
表中。
3. 開發(fā)流程
- 工具類:編寫多個(重載)JSONString 相關(guān)的方法
- 數(shù)據(jù)庫交互:在 xxxmapper.xml 文件中編寫對應(yīng)的 SQL 語句,并在 Dao 層的接口中聲明 CRUD 方法
- 核心業(yè)務(wù)邏輯:在 Service 層中編寫,由該層調(diào)用 Dao 層的方法實現(xiàn)對數(shù)據(jù)層的操作
- 視圖層:控制器 + 頁面
4. 引入AJAX依賴
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.58</version> </dependency>
5. Util
util/CommunityUtil.java
在用戶登錄之前,不顯示【發(fā)布帖子】按鈕;
在用戶登錄之后,才顯示【發(fā)布帖子】按鈕,可以進行相關(guān)操作。
//得到JSON格式的字符串 //輸入為:編號、提示、業(yè)務(wù)數(shù)據(jù) 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:無業(yè)務(wù)數(shù)據(jù)) public static String getJSONString(int code, String msg){ return getJSONString(code, msg, null); } //得到JSON格式的字符串(重載2:無提示、業(yè)務(wù)數(shù)據(jù)) 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注解用于給參數(shù)取別名 // 如果只有一個參數(shù),并且在<if>里使用,則必須加別名 int selectDiscussPostRows(@Param("userId") int userId); int insertDiscussPost(DiscussPost discussPost); }
mapper/discusspost-mapper.xml
編寫對應(yīng)的 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("參數(shù)不能為空!"); } // 轉(zhuǎn)義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; //處理所有與發(fā)帖相關(guān)的請求 @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表示沒有權(quán)限 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, "發(fā)布成功"); } }
9. JavaScript
index.js
在 js 文件中編寫【發(fā)布按鈕】對應(yīng)的函數(shù) publish()
$(function(){ $("#publishBtn").click(publish); }); function publish() { $("#publishModal").modal("hide"); // 獲取標題和內(nèi)容 var title = $("#recipient-name").val(); var content = $("#message-text").val(); // 發(fā)送異步請求(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); } ); }
到此這篇關(guān)于SpringBoot采用AJAX實現(xiàn)異步發(fā)布帖子詳解的文章就介紹到這了,更多相關(guān)SpringBoot AJAX內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
MySQL數(shù)據(jù)文件直接通過拷貝備份與恢復(fù)的操作方法
這篇文章主要介紹了MySQL數(shù)據(jù)文件直接通過拷貝備份與恢復(fù)的操作方法,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09java數(shù)組與以逗號分隔開的字符串的相互轉(zhuǎn)換操作
這篇文章主要介紹了java數(shù)組與以逗號分隔開的字符串的相互轉(zhuǎn)換操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09Java SpringCache+Redis緩存數(shù)據(jù)詳解
本篇文章主要介紹了淺談SpringCache與redis緩存數(shù)據(jù)的解決方案,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2021-10-10