AJAX?SpringBoot?前后端數(shù)據(jù)交互的項目實現(xiàn)
1. Ajax 概述
Ajax 的英文全稱是 ”Asynchronous JavaScript and XML“,即 ”異步的 JavaScript 和 XML“。其核心是通過 JavaScript 的 XMLHttpRequest 對象,以一種異步的方式,向服務器發(fā)送數(shù)據(jù)請求,并且通過該對象接收請求返回的數(shù)據(jù),從而實現(xiàn)客戶端與服務器端的數(shù)據(jù)交互。
優(yōu)點:Ajax 能夠刷新指定的頁面區(qū)域(局部刷新),而不是刷新整個頁面,從而減少客戶端和服務器端之間的數(shù)據(jù)交互傳輸,提高頁面速度,使得用戶體驗更好。
初體驗:基于 jQuery 方式動態(tài)綁定事件提交
給【獲取驗證碼】按鈕綁定點擊事件,當用戶點擊該按鈕時,向后臺服務器發(fā)送 AJAX 請求獲取一個隨機驗證碼,登錄頁面的整體不重新加載,僅做局部的頁面刷新。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>異步請求</title> <script type="text/javascript" src="/static/js/jquery-2.0.0.min.js"></script> <script type="text/javascript"> $(function () { var btn = $("#flush"); btn.click(function () { $.ajax({ url: '/getCode', type:'get', data:'id=1', //字符串 dataType:'text', success:function (data) { console.log(data); alert("后臺驗證碼:" + data); } }) }) }) </script> </head> <body> <div style="text-align: center;"> <h2>用戶登錄</h2> <form> 用戶名:<input type="text" name="username"><br> 密 碼:<input type="password" name="password"><br> 驗證碼:<input type="text" name="code"><br><br> <input type="button" value="登錄"> <input type="button" id="flush" value="獲取驗證碼"> </form> </div> </body> </html>
SpringBoot 后臺接收 AJAX 請求,首先要獲取該請求攜帶的參數(shù) id=1
(該參數(shù)沒有實際意義,僅做演示使用),然后根據(jù)請求業(yè)務,對該結(jié)果進行響應。success
回調(diào)函數(shù)對響應結(jié)果進行展示。
import javax.servlet.http.HttpServletRequest; import java.util.Random; @Controller public class TestController { @GetMapping("/ajax") public String index(){ return "form"; } //SpringBoot接收ajax請求的方式 //方式一:使用HttpServletRequest request接收請求參數(shù) @GetMapping("/getCode") @ResponseBody public String getCode(HttpServletRequest request){ String id = request.getParameter("id"); System.out.println("AJAX傳遞的參數(shù):" + id); //獲取5位驗證碼 return randomCodes(); } //方式二:用@Param映射單個值 @GetMapping("/getCode1") @ResponseBody public String getCode1(@Param("id") Integer id){ System.out.println(id); //獲取5位驗證碼 return randomCodes(); } public String randomCodes(){ String str="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; StringBuilder code=new StringBuilder(5); for(int i=0;i<5;i++) { char ch=str.charAt(new Random().nextInt(str.length())); code.append(ch); } return code.toString(); } }
上面介紹了兩種 SpringBoot 接收請求參數(shù)的方式:
public String getCode(HttpServletRequest request)
:使用 HttpServletRequest request 接收請求參數(shù);public String getCode1(@Param("id") Integer id)
:用 @Param 映射單個值;
Ajax 異步請求一個典型的應用就是用戶表單輸入時,局部刷新驗證碼,而不會影響其他表單項已輸入的信息。
傳統(tǒng)的 WEB 數(shù)據(jù)交互與 AJAX 數(shù)據(jù)交互比較:
- 客戶端請求的方式不同:傳統(tǒng)的 WEB 是用瀏覽器發(fā)送同步數(shù)據(jù)請求(form表單、a鏈接),AJAX 是異步引擎對象發(fā)送異步請求;
- 服務器響應的方式不同:傳統(tǒng)的 WEB 每次響應的是一個完整的 HTML 頁面即視圖,AJAX 是局部刷新,返回響應需要的 JSON 數(shù)據(jù);
- 客戶端處理方式不同:傳統(tǒng)的 WEB 需要等待服務器完成響應并且重新加載整個頁面之后,用戶才能進行后續(xù)操作,AJAX 動態(tài)更新頁面中的局部內(nèi)容,不影響用戶的其他操作;
2. 基于 JQuery 的 AJAX 語法
$.ajax({屬性})
常用的屬性參數(shù):
參數(shù) | 描述 |
---|---|
url | 請求后端服務器的地址 |
type | 請求方式,默認為 get 類型 |
data | 請求參數(shù) |
dataType | 服務器返回的數(shù)據(jù)類型,比如:text/json/xml 等 |
success | 請求成功的回調(diào)函數(shù) |
error | 請求失敗的回調(diào)函數(shù) |
complete | 請求完成的回調(diào)函數(shù)(無論成功還是失敗,都會被調(diào)用) |
用法示例(服務器與客戶端之間的數(shù)據(jù)交互類型是JSON):
$.ajax({ url:'/search', type:'post', data:{ 'id':$("#sid").val(), 'username':$("#uname").val(), 'password':$("#pwd").val() }, dataType:'json', success:function (data) { console.log(data); $("#sid").val(data.id); $("#uname").val(data.name); $("#score").val(data.score); } })
JSON(JavaScript Object Notation),一種輕量級數(shù)據(jù)交互格式,完成 js 與 Java/Python/PHP 等后端開 發(fā)語言對象數(shù)據(jù)之間的轉(zhuǎn)換。客戶端與服務器之間傳遞對象數(shù)據(jù)時,需要使用 JSON 格式。
案例:使用 AJAX 校驗用戶輸入的信息,編寫一個 2022 年碩士研究生招生考試成績查詢系統(tǒng);
1、創(chuàng)建空白的 SpringBoot 項目,并在 pom.xml 導入相關(guān)依賴;
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>3.4.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency>
2、在 MySQL 數(shù)據(jù)庫中創(chuàng)建一張考研成績數(shù)據(jù)表(stu_score),并錄入若干條測試數(shù)據(jù);
3、在全局配置文件 resources/application.yml 中配置數(shù)據(jù)源信息、視圖解析器以及端口號等相關(guān)配置等;
spring: thymeleaf: prefix: classpath:/templates/ suffix: .html mode: HTML5 encoding: UTF-8 datasource: url: jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8 username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver mvc: static-path-pattern: /static/** server: port: 8181 # 配置SQL日志 mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
4、創(chuàng)建數(shù)據(jù)表對應的實體類 Student;
package com.trainingl.entity; import com.baomidou.mybatisplus.annotation.TableName; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @NoArgsConstructor @AllArgsConstructor @TableName(value = "stu_score") public class Student { @TableId(type = IdType.ASSIGN_ID) private Long sid; private String sname; private String card; private Integer politics; private Integer english; private Integer math; private Integer computer; }
5、在路徑 com > trainingl > mapper 下創(chuàng)建接口 StudentMapper;
package com.trainingl.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.trainingl.entity.Student; import org.springframework.stereotype.Repository; @Repository public interface StudentMapper extends BaseMapper<Student> { //所有的CRUD操作都已經(jīng)編寫好了 }
說明:由于系統(tǒng)規(guī)模較小,所以這里省略了 Service 服務層。
6、創(chuàng)建 SearchController 控制器,主要負責接收客戶端瀏覽器的 AJAX 請求與響應。
package com.trainingl.controller; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.trainingl.entity.Student; import com.trainingl.mapper.StudentMapper; import org.apache.ibatis.annotations.Param; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import java.util.HashMap; import java.util.Map; @Controller @RequestMapping("/suda") public class SearchController { @Autowired private StudentMapper studentMapper; @GetMapping("/search") public String home(){ return "login"; } @PostMapping("/login") @ResponseBody public Map<String,String> login(HttpServletRequest request){ String id = request.getParameter("id"); String username = request.getParameter("username"); String card = request.getParameter("password"); //查詢判斷 QueryWrapper<Student> wrapper = new QueryWrapper<>(); wrapper .eq("sid",id) .eq("sname", username) .eq("card", card); Integer count = studentMapper.selectCount(wrapper); //返回值 HashMap<String, String> map = new HashMap<>(); if (count == 1){ //登錄驗證成功,通過id查詢該考生的成績(id具有唯一性) map.put("result", id); map.put("code","100"); }else { map.put("result","登錄失?。≥斎胄畔⒂姓`!"); map.put("code","200"); } return map; } @GetMapping("/searchById/{id}") public ModelAndView searchById(@PathVariable Long id){ ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("person"); Student student = studentMapper.selectById(id); System.out.println(student); Integer total = student.getPolitics() + student.getEnglish() + student.getMath() + student.getComputer(); modelAndView.addObject("student", student); modelAndView.addObject("totalScore", total); return modelAndView; } }
7、視圖層(系統(tǒng)登錄頁面、成績查詢頁面)
7.1 系統(tǒng)登錄頁面(客戶端與服務器之間的數(shù)據(jù)交互格式是JSON,請求方式是AJAX,而不是通過form表單完成)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>系統(tǒng)登錄</title> <script type="text/javascript" src="/static/js/jquery-2.0.0.min.js"></script> <script type="text/javascript"> $(function () { var btn = $("#btn"); // 點擊事件 btn.click(function () { $.ajax({ url:'/suda/login', type:'post', data:{ 'id':$("#sid").val(), 'username':$("#uname").val(), 'password':$("#pwd").val() }, dataType:'json', success:function (data) { if(data.code == "100"){ //登錄成功,則跳轉(zhuǎn)到成績查詢頁面 window.location.href = "/suda/searchById/" + data.result; }else{ //登錄失敗,則給出提示信息 var msg = $("#btn"); msg.after("<br><br><span style='color:red;'>提示:"+data.result+"</span>") } } }) }) }) </script> </head> <body> <div style="text-align:center;"> <img src="/static/img/brand.png" style="width: 280px;height: 100px;"/> <h3>2022年碩士研究生招生考試成績查詢系統(tǒng)</h3> <img src="/static/img/logo.jpeg" style="width: 500px;height: 300px;"/> <!--這里不通過form表單提交客戶端請求--> <form> 準考證號:<input type="text" name="id" id="sid"><br> 考生姓名:<input type="text" name="username" id="uname"><br> 身份證號:<input type="text" name="password" id="pwd"><br/> <br/> <input type="button" value="查詢" id="btn"> </form> </div> </body> </html>
注:如果輸入的信息校驗失敗,則通過紅色字體給出提示,若信息校驗成功,則會跳轉(zhuǎn)到初試成績的詳細界面。
7.2 成績詳細頁面(通過 thymeleaf 模板渲染數(shù)據(jù))
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.w3.org/1999/xhtml"> <html xmlns:th="http://www.thymeleaf.org"></html> <head> <meta charset="UTF-8"> <title>研究生初試成績查詢</title> </head> <body> <div style="text-align: center;"> <div style="border: 1px solid;"> <h3>2022年研究生考試初始成績查詢</h3> <br> 準考證號:<span th:text="${student.sid}"></span><br> 姓名:<span th:text="${student.sname}"></span><br> 身份證號:<span th:text="${student.card}"></span><br> <hr/> 思想政治理論:<span th:text="${student.politics}"></span><br> 英語(一):<span th:text="${student.english}"></span><br> 數(shù)學(一):<span th:text="${student.math}"></span><br> 計算機科學專業(yè)基礎(chǔ)(408):<span th:text="${student.computer}"></span><br> 總分:<span th:text="${totalScore}"></span><br> </div> <p>說明:若查詢的成績?yōu)樨撝?表示有缺考、違紀等情況。若仍對查詢結(jié)果有疑問,請咨詢相應的招生單位。 </p> </div> </body> </html>
總結(jié):本項目用于演示 AJAX 與 SpringBoot 項目前后端數(shù)據(jù)交互,以案例+項目驅(qū)動的方式介紹了在 SpringBoot 項目開發(fā)中異步請求前后端數(shù)據(jù)的傳遞方式。
到此這篇關(guān)于AJAX SpringBoot 前后端數(shù)據(jù)交互的項目實現(xiàn)的文章就介紹到這了,更多相關(guān)AJAX SpringBoot 數(shù)據(jù)交互內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- jquery+ajaxform+springboot控件實現(xiàn)數(shù)據(jù)更新功能
- SpringBoot解決ajax跨域問題的方法
- Springboot解決ajax+自定義headers的跨域請求問題
- SpringBoot基于Shiro處理ajax請求代碼實例
- SpringBoot結(jié)合Ajax實現(xiàn)登錄頁面實例
- SpringBoot+Hutool+thymeleaf完成導出Excel的實現(xiàn)方法
- SpringBoot + thymeleaf 實現(xiàn)讀取視頻列表并播放視頻功能
- springboot如何使用thymeleaf完成頁面緩存
- SpringBoot+Thymeleaf+ECharts實現(xiàn)大數(shù)據(jù)可視化(基礎(chǔ)篇)
- 在SpringBoot中配置Thymeleaf的模板路徑方式
- SpringBoot+thymeleaf+ajax實現(xiàn)局部刷新詳情
相關(guān)文章
解決springboot 無法配置多個靜態(tài)路徑的問題
這篇文章主要介紹了解決springboot 無法配置多個靜態(tài)路徑的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-08-08spring boot 防止重復提交實現(xiàn)方法詳解
這篇文章主要介紹了spring boot 防止重復提交實現(xiàn)方法,結(jié)合實例形式詳細分析了spring boot 防止重復提交具體配置、實現(xiàn)方法及操作注意事項,需要的朋友可以參考下2019-11-11Spring Boot訪問靜態(tài)資源css/js,你真的懂了嗎
在搭建springboot時經(jīng)常需要在html中訪問一些靜態(tài)資源,很多朋友不清楚如何在 Spring Boot中訪問靜態(tài)資源,本文給大家?guī)韮煞N解決方案,感興趣的朋友跟隨小編一起看看吧2021-05-05利用java和sqlserver建立簡易圖書管理系統(tǒng)的完整步驟
圖書館管理系統(tǒng)是圖書館管理工作中不可缺少的部分,它對于圖書館的管理者和使用者都非常重要,下面這篇文章主要給大家介紹了關(guān)于利用java和sqlserver建立簡易圖書管理系統(tǒng)的完整步驟,需要的朋友可以參考下2022-06-06詳解java集成支付寶支付接口(JSP+支付寶20160912)
本篇文章主要介紹了java集成支付寶支付接口,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-12-12