SpringMVC和Ajax的交互詳解(手工處理)
SpringMVC與Ajax的交互
一、ajax的實(shí)現(xiàn)
ajax異步請(qǐng)求 javaScript and xml 異步請(qǐng)求
1、同步請(qǐng)求和異步請(qǐng)求
1、異步請(qǐng)求 特點(diǎn):請(qǐng)求響應(yīng)回來(lái)頁(yè)面不動(dòng) 只刷新頁(yè)面局部
2、同步請(qǐng)求 特點(diǎn):響應(yīng)回來(lái)全部刷新(地址欄,超鏈接,表單 js的location.href="")
3、通過(guò)Ajax發(fā)送的請(qǐng)求都是異步請(qǐng)求 多請(qǐng)求之間并行處理 請(qǐng)求之間不會(huì)相互影響
2、Ajax實(shí)現(xiàn)異步請(qǐng)求
Ajax發(fā)送請(qǐng)求 通過(guò)js的異步請(qǐng)求對(duì)象發(fā)送請(qǐng)求 xhr XMLHttpRequest
js實(shí)現(xiàn)ajax:
1、創(chuàng)建異步請(qǐng)求對(duì)象 xhr
2、準(zhǔn)備并且發(fā)送請(qǐng)求xhr.open() xhr.send();
3、處理響應(yīng)
xhr.onreadyStateChang=dunction(){
if(xhr.readyState==4&&xhr.status==200{
xhr.responseText
}
}
4、ajax只認(rèn)字符串
jquery實(shí)現(xiàn)Ajax的封裝
$.ajax({}) 基礎(chǔ)發(fā)送Ajax請(qǐng)求的方式
$.get(url,method,function(){})//get方式發(fā)送請(qǐng)求
$.post(url,method,function{},"json")
二、SpringMVC和AJAX交互(手工處理)
控制器使用的json解析工具:阿里巴巴的fastjson
<!--引入阿里巴巴json解析器fastjson-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
1、案例:使用Ajax形式查詢所有用戶
(1)交互示意圖

(2)ajax頁(yè)面
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<%--引入js相關(guān)的jquery頁(yè)面--%>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.min.js"></script>
<script type="text/javascript">
$(function () {
//獲取單擊按鈕對(duì)象,綁定單擊事件
$("#btn").click(function () {
//發(fā)送get形式的Ajax異步請(qǐng)求
$.get("${pageContext.request.contextPath}/user/show", function (result) {
console.log(result)
}, "json");
})
});
</script>
</head>
<body>
<input type="button" value="點(diǎn)擊查詢所有" id="btn">
</body>
</html>
(3)實(shí)體類
public class User {
private Integer id;
private String Username;
private String password;
private Double salary;
private Date birthday;(4)Controller以手工轉(zhuǎn)化json
@Controller
@RequestMapping("user")
public class QueryUser {
@RequestMapping("show")
public String showUser(HttpServletResponse response) throws IOException {
User user1 = new User(1,"王恒杰1","123",2000d,new Date());
User user2 = new User(2,"王恒杰2","123",20000d,new Date());
User user3 = new User(3,"王恒杰3","123",200000d,new Date());
User user4 = new User(4,"王恒杰4","123",2000000d,new Date());
User user5 = new User(5,"王恒杰5","123",20000000d,new Date());
List<User> users = Arrays.asList(user1, user2, user3, user4, user5);
//1、將users用戶集合轉(zhuǎn)化為json形式字符串
String jsonUsers = JSONObject.toJSONStringWithDateFormat(users, "yyyy-mm-dd");
//2、通過(guò)響應(yīng)輸出流,響應(yīng)到客戶端
//設(shè)置響應(yīng)格式
response.setCharacterEncoding("utf-8");
response.getWriter().print(jsonUsers);
return null;
}
}
(5)響應(yīng)到前端中文亂碼 Ajax前端頁(yè)面響應(yīng)中文亂碼

響應(yīng)之前先設(shè)置響應(yīng)格式:
//設(shè)置響應(yīng)格式
response.setCharacterEncoding("utf-8");

解決亂碼問(wèn)題后

三、SpringMVC和AJAX交互(@responseBody注解實(shí)現(xiàn))
1、SpringMVC提供注解:@responseBody
@responseBody:簡(jiǎn)化返回的數(shù)據(jù)轉(zhuǎn)化成json串并且通過(guò)response響應(yīng)的回客戶端過(guò)程

2、使用@ResponseBody替代手工處理(使用Ajax形式查詢所有用戶)
@Controller
@RequestMapping("user")
public class QueryUser {
@RequestMapping("show")
@ResponseBody
public List<User> showUser(HttpServletResponse response) throws IOException {
User user1 = new User(1,"王恒杰1","123",2000d,new Date());
User user2 = new User(2,"王恒杰2","123",20000d,new Date());
User user3 = new User(3,"王恒杰3","123",200000d,new Date());
User user4 = new User(4,"王恒杰4","123",2000000d,new Date());
User user5 = new User(5,"王恒杰5","123",20000000d,new Date());
List<User> users = Arrays.asList(user1, user2, user3, user4, user5);
return users;
}
}
@ResponseBody替代示意圖

3、@responsBody注意事項(xiàng)
(1)@responsBody注解 使用的json轉(zhuǎn)化工具 不是fastjson,用的是jackjson
<!--jackson相關(guān)依賴 Springmvc@responsBody注解使用jackSon-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.3</version>
</dependency>
(2)@responsBody可以放在返回值前面

(3)設(shè)置當(dāng)前方式的日期轉(zhuǎn)化格式需要使用注解

//jackson SpringMVC內(nèi)置的 @JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8") //fastjson 阿里的 @JSONFiled(format="yyyy-mm-dd")
解決辦法:在實(shí)體類的屬性Date加入:@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")

設(shè)置后結(jié)果:

4、@ResponseBody案例:通過(guò)動(dòng)態(tài)獲取id查詢用戶并在頁(yè)面顯示結(jié)果
(1)前端頁(yè)面動(dòng)態(tài)獲取id,通過(guò)Ajax實(shí)現(xiàn)異步傳輸id值到Controller層
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.8.3.min.js"></script>
<script>
$(function () {
$("#del").click(function () {
$.get("${pageContext.request.contextPath}/user/showById?id=" + $("input[name='id']").val(), function (result) {
console.log(result);
// 創(chuàng)建ul標(biāo)簽
var ul = $("<ul></ul>");
// 創(chuàng)建li當(dāng)前獲取到的值
var idLi = $("<li>" + result.id + "</li>");
var usernameLi = $("<li>" + result.username + "</li>");
var passwordLi = $("<li>" + result.password + "</li>");
var salaryLi = $("<li>" + result.salary + "</li>");
var birthdayLi = $("<li>" + result.birthday + "</li>");
// 將li子標(biāo)簽添加到ul上
ul.append(idLi);
ul.append(usernameLi);
ul.append(passwordLi);
ul.append(salaryLi);
ul.append(birthdayLi);
$("#body").append(ul)
}, "json");
})
})
</script>
</head>
<body id="body">
ID:<input type="text" name="id" placeholder="請(qǐng)輸入用戶的ID">
<input type="button" name="id" value="提交" id="del">
</body>
</html>(2)控制層java代碼
@RequestMapping("showById")
public @ResponseBody User showUserById(HttpServletResponse response,Integer id) throws IOException {
User user1 = new User(1,"王恒杰1","123",2000d,new Date());
User user2 = new User(2,"王恒杰2","123",20000d,new Date());
User user3 = new User(3,"王恒杰3","123",200000d,new Date());
User user4 = new User(4,"王恒杰4","123",2000000d,new Date());
User user5 = new User(5,"王恒杰5","123",20000000d,new Date());
List<User> users = Arrays.asList(user1, user2, user3, user4, user5);
for (User user : users) {
if(id.equals(user.getId())){
return user;
}
}
return null;
}
(3)效果展示圖

總結(jié)
到此這篇關(guān)于SpringMVC和Ajax交互的文章就介紹到這了,更多相關(guān)SpringMVC和Ajax交互內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot整合minio實(shí)現(xiàn)文件存儲(chǔ)功能
MinIO?是一個(gè)基于Apache?License?v2.0開源協(xié)議的對(duì)象存儲(chǔ)服務(wù),它兼容亞馬遜S3云存儲(chǔ)服務(wù)接口,非常適合于存儲(chǔ)大容量非結(jié)構(gòu)化的數(shù)據(jù),本文給大家介紹了springboot整合minio實(shí)現(xiàn)文件存儲(chǔ)功能,文中通過(guò)代碼示例介紹的非常詳細(xì),需要的朋友可以參考下2023-12-12
Spring Aop之AspectJ注解配置實(shí)現(xiàn)日志管理的方法
下面小編就為大家分享一篇Spring Aop之AspectJ注解配置實(shí)現(xiàn)日志管理的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
Java中面向?qū)ο蟮闹R(shí)點(diǎn)總結(jié)
Java是一門面向?qū)ο蟮恼Z(yǔ)言。對(duì)象是Java程序中的基本實(shí)體。除了對(duì)象之外Java程序同樣處理基本數(shù)據(jù)。下面這篇文章主要給大家總結(jié)了關(guān)于Java中面向?qū)ο蟮闹R(shí)點(diǎn),需要的朋友可以參考借鑒,下面來(lái)一起看看吧。2017-02-02
idea在運(yùn)行期間,實(shí)現(xiàn)讓修改的頁(yè)面實(shí)時(shí)生效
這篇文章主要介紹了idea在運(yùn)行期間,實(shí)現(xiàn)讓修改的頁(yè)面實(shí)時(shí)生效問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01
java設(shè)計(jì)模式之外觀模式學(xué)習(xí)筆記
這篇文章主要為大家詳細(xì)介紹了java設(shè)計(jì)模式之外觀模式學(xué)習(xí)筆記,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-10-10
spring配置文件中util:properties和context:property-placeholder用法
這篇文章主要介紹了spring配置文件中util:properties和context:property-placeholder用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01

