欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot采用AJAX實(shí)現(xiàn)異步發(fā)布帖子詳解

 更新時(shí)間:2022年08月23日 15:17:32   作者:LeBron Le  
Ajax是一種web應(yīng)用技術(shù),可以借助客戶端腳本(javascript)與服務(wù)端應(yīng)用進(jìn)行異步通訊,獲取服務(wù)端數(shù)據(jù)以后,可以進(jìn)行局部刷新,進(jìn)而提高數(shù)據(jù)的響應(yīng)和渲染速度。所有的Ajax請(qǐng)求都會(huì)基于DOM(HTML元素)事件,通過XHR(XMLHttpRequest)對(duì)象實(shí)現(xiàn)與服務(wù)端異步通訊局部更新

1. AJAX

  • Asynchronous JavaScript and XML
  • 異步的 JavaScript 與 XML 不是一門新技術(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è)面并沒有刷新。

點(diǎn)擊【發(fā)布帖子】按鈕后,publishBtn 按鈕會(huì)執(zhí)行 index.js 中的 publish() 方法,跳轉(zhuǎn)到:CONTEXT_PATH + “/discuss/add”;會(huì)執(zhí)行控制器類 DiscussPostControlleraddDiscussPost()方法。里面調(diào)用Service: discussPostService,該service又調(diào)用了 discussPostMapper,通過其對(duì)應(yīng)的 SQL 語(yǔ)句將帖子內(nèi)容插進(jìn) discuss_post 表中。

3. 開發(fā)流程

  • 工具類:編寫多個(gè)(重載)JSONString 相關(guān)的方法
  • 數(shù)據(jù)庫(kù)交互:在 xxxmapper.xml 文件中編寫對(duì)應(yīng)的 SQL 語(yǔ)句,并在 Dao 層的接口中聲明 CRUD 方法
  • 核心業(yè)務(wù)邏輯:在 Service 層中編寫,由該層調(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:無業(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ù)取別名
    // 如果只有一個(gè)參數(shù),并且在<if>里使用,則必須加別名
    int selectDiscussPostRows(@Param("userId") int userId);
    int insertDiscussPost(DiscussPost discussPost);
}

mapper/discusspost-mapper.xml

編寫對(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

編寫 addDiscussPost(),同時(shí)注入過濾器

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()));
        // 過濾敏感詞
        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表示沒有權(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ā)布按鈕】對(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ù)文件直接通過拷貝備份與恢復(fù)的操作方法

    MySQL數(shù)據(jù)文件直接通過拷貝備份與恢復(fù)的操作方法

    這篇文章主要介紹了MySQL數(shù)據(jù)文件直接通過拷貝備份與恢復(fù)的操作方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-09-09
  • java數(shù)組與以逗號(hào)分隔開的字符串的相互轉(zhuǎn)換操作

    java數(shù)組與以逗號(hào)分隔開的字符串的相互轉(zhuǎn)換操作

    這篇文章主要介紹了java數(shù)組與以逗號(hào)分隔開的字符串的相互轉(zhuǎn)換操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • 深入理解可視化JVM 故障處理工具

    深入理解可視化JVM 故障處理工具

    這篇文章主要介紹了深入理解可視化JVM 故障處理工具,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • Spring Boot 項(xiàng)目啟動(dòng)失敗的解決方案

    Spring Boot 項(xiàng)目啟動(dòng)失敗的解決方案

    這篇文章主要介紹了Spring Boot 項(xiàng)目啟動(dòng)失敗的解決方案,幫助大家更好的理解和學(xué)習(xí)使用Spring Boot,感興趣的朋友可以了解下
    2021-03-03
  • Java SpringCache+Redis緩存數(shù)據(jù)詳解

    Java SpringCache+Redis緩存數(shù)據(jù)詳解

    本篇文章主要介紹了淺談SpringCache與redis緩存數(shù)據(jù)的解決方案,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2021-10-10
  • Java之IO流面試題案例講解

    Java之IO流面試題案例講解

    這篇文章主要介紹了Java之IO流案例講解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-07-07
  • SpringBoot使用protobuf格式的接口方式

    SpringBoot使用protobuf格式的接口方式

    這篇文章主要介紹了SpringBoot使用protobuf格式的接口方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Java Date類的使用案例詳解

    Java Date類的使用案例詳解

    這篇文章主要介紹了Java Date類的使用案例詳解,本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • 帶你了解10道java入門面試題

    帶你了解10道java入門面試題

    面試題相信大家都不陌生,想要一個(gè)好的工作面試題必不可少的,下面和小編一起來學(xué)習(xí)與了解Java當(dāng)中有有些什么面試題吧,希望能給你帶來幫助
    2021-08-08
  • 淺談Spring-boot事件監(jiān)聽

    淺談Spring-boot事件監(jiān)聽

    這篇文章主要介紹了淺談Spring-boot事件監(jiān)聽,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-09-09

最新評(píng)論