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

