SpringMVC-Ajax

SpringMVC-Ajax

1. Ajax简介

  • Ajax = Asynchronous JavaScript and XML(异步的JavaScript和XML)

  • Ajax是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。

  • Ajax不是一种新的编程语言,而是一种用于创建更好更快以及交互性更强的Web应用程序的奇数。

  • 在2005年,Google通过其Google使得Ajax变得流行起来,Google Suggest能够自动帮你完成搜索单词。

2. 伪Ajax

通过iframe标签伪造一个ajax的样子

环境搭建:新建一个工程(添加Web依赖)

  1. web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">

<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>


<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>


<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

</web-app>
  1. 配置applicationContext.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
<context:component-scan base-package="com.zhuuu.controller"/>
<!--静态资源过滤-->
<mvc:default-servlet-handler/>


<!--处理json乱码-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>



<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 后缀 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
  1. 测试Tomcat配置是否能成功
1
2
3
4
5
6
7
@RestController
public class AjaxController {
@RequestMapping("/t1")
public String test(){
return "hello";
}
}
  1. 编写一个iframe.html测试,感受下效果
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>iframe体验页面无刷新</title>

<script>
function go() {
//所有的值变量,提前获取
var url = document.getElementById("url").value;
document.getElementById("iframe1").src= url;
}
</script>

</head>
<body>

<div>
<p>请输入地址:</p>
<p>
<input type="text" id="url" value="http://zhuuu.work/">
<input type="button" value="提交" onclick="go()">
</p>
</div>

<div>
<iframe id="iframe1" src="https://www.baidu.com/" frameborder="0" style="width: 100%;height: 500px"></iframe>
</div>
</body>
</html>

3. jQuery.ajax

  • 纯Ajax原生实现这里不去讨论,直接使用jQuery提供的,方便学习和使用,避免重复造轮子
  • Ajax的核心是XMLHttpRequest对象(XHR),XHR为向服务器发送请求和解析服务器响应提供了接口,能够以异步方式从服务器获取新数据。
  • jQuery提供了多个与Ajax有关的方法。
  • 通过jQuery Ajax方法,你能够使用Http Get和 Http Post从远程服务器上请求文本,HTML,XML和Json。同时能够把这些外部数据直接载入到网页的被选元素中。
  • jQuery不是生产者,只是搬运工。
  • jQuery Ajax本质是XMLHttpRequest,对他进行了封装。
1
2
//语法
$.ajax({name:value, name:value, ... })
名称
async 布尔值,表示请求是否异步处理。默认是 true。
beforeSend(xhr) 发送请求前运行的函数。
cache 布尔值,表示浏览器是否缓存被请求页面。默认是 true。
complete(xhr,status) 请求完成时运行的函数(在请求成功或失败之后均调用,即在 success 和 error 函数之后)。
contentType 发送数据到服务器时所使用的内容类型。默认是:”application/x-www-form-urlencoded”。
context 为所有 AJAX 相关的回调函数规定 “this” 值。
data 规定要发送到服务器的数据。
dataFilter(data,type) 用于处理 XMLHttpRequest 原始响应数据的函数。
dataType 预期的服务器响应的数据类型。
error(xhr,status,error) 如果请求失败要运行的函数。
global 布尔值,规定是否为请求触发全局 AJAX 事件处理程序。默认是 true。
ifModified 布尔值,规定是否仅在最后一次请求以来响应发生改变时才请求成功。默认是 false。
jsonp 在一个 jsonp 中重写回调函数的字符串。
jsonpCallback 在一个 jsonp 中规定回调函数的名称。
password 规定在 HTTP 访问认证请求中使用的密码。
processData 布尔值,规定通过请求发送的数据是否转换为查询字符串。默认是 true。
scriptCharset 规定请求的字符集。
success(result,status,xhr) 当请求成功时运行的函数。
timeout 设置本地的请求超时时间(以毫秒计)。
traditional 布尔值,规定是否使用参数序列化的传统样式。
type 规定请求的类型(GET 或 POST)。
url 规定发送请求的 URL。默认是当前页面。
  1. 下载jQuery并在文件中引用
1
2
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js">
</script>
  1. 具体示例(去后台判断输入)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>

<script>
function a(){
$.post({
url:"${pageContext.request.contextPath}/a1",
data:{"name":$("#username").val()},
success: function (data) {
alert(data);
}
})
}
</script>
<title>$Title$</title>
</head>
<body>

<%--失去焦点的时候,发起一个请求到后台--%>

用户名:<input type="text" id="username" onblur="a()">

</body>
</html>
1
2
3
4
5
6
7
8
@RequestMapping("/a1")
public void a1(String name, HttpServletResponse response) throws IOException {
System.out.println("a1:param--->"+name);
if("zhuuu".equals(name)){
response.getWriter().print("true");
}else
response.getWriter().print("false");
}

js源码分析:

流程 原理分析:

  • Ajax把主动权交给了前端
  • Ajax实现了前后端分离,异步刷新
  • 后台返回一个json字符串
  • 前端携带参数给后端

3.1 Ajax测试实体类

  1. 新建一个pojo类下的User.java
1
2
3
4
5
6
7
8
9
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

private String name;
private int age;
private String gender;
}
  1. controller去获取实体类
1
2
3
4
5
6
7
8
9
10
11
@RequestMapping("/a2")
public List<User> a2(){
ArrayList<User> userlist = new ArrayList<User>();

//添加数据
userlist.add(new User("朱酱酱",3,"man"));
userlist.add(new User("前端",2,"man"));
userlist.add(new User("后端",1,"man"));

return userlist;
}

这样仅仅返回给前端一个json字符串

接下来需要前端进行处理

  1. 新建测试ajaxTest2.jsp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<html>
<head>
<title>Title</title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>

<script>

$(function () {
//触发点击事件
$("#btn").click(function () {
$.post("${pageContext.request.contextPath}/a2",function (data) {
console.log(data)
var html="";
for (var i = 0; i <data.length ; i++) {
html+= "<tr>" +
"<td>" + data[i].name + "</td>" +
"<td>" + data[i].age + "</td>" +
"<td>" + data[i].gender + "</td>" +
"</tr>"
}
$("#content").html(html);
});
})
})
</script>

</head>
<body>

<input type="button" value="加载数据" id="btn">
<table>
<tr>
<td>姓名</td>
<td>年龄</td>
<td>性别</td>
</tr>
<tbody id="content">
<%--数据在后台,拿到数据之后显示在这里--%>
</tbody>
</table>
</body>
</html>

本质:前端解析Json字符串显示到前端

3.2 Ajax动态验证登录判断

  1. 编写登录页面(login.jsp)
1
2
3
4
5
6
7
8
9
10
11
<body>
<p>
用户名:<input type="text" id="name" onblur="a1()">
<span id="userinfo"></span>
</p>

<p>
密码:<input type="text" id="pwd" onblur="a2()">
<span id="pwdInfo"></span>
</p>
</body>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<head>
<title>登录页面Ajax</title>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.4.1.js"></script>

<script>
function a1() {
$.post({
url: "${pageContext.request.contextPath}/a3",
data: {"name":$("#name").val()}, //传送数据到后台
success:function (data) {
if(data.toString()==="ok"){
$("#userinfo").css("color","green");
}else {
$("#userinfo").css("color","red");
}
$("#userinfo").html(data);
}
})
}

function a2() {
$.post({
url: "${pageContext.request.contextPath}/a3",
data: {"pwd":$("#pwd").val()}, //传送数据到后台
success:function (data) {
if(data.toString()==="ok"){
$("#pwdInfo").css("color","green");
}else {
$("#pwdInfo").css("color","red");
}
$("#pwdInfo").html(data);
}
})
}
</script>
</head>
  1. 编写对应的后台判断
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@RequestMapping("/a3")
public String a3(String name,String pwd){
String msg = "";
if(name!=null){
//这些数据本来应该在数据库中查
if("admin".equals(name)){
msg = "ok";
}else{
msg = "输入有误";
}
}
if(pwd!=null){
//这些数据本来应该在数据库中查
if("123456".equals(pwd)){
msg = "ok";
}else{
msg = "false";
}
}
return msg;
}
打赏
  • 版权声明: 本博客所有文章除特别声明外,均采用 Apache License 2.0 许可协议。转载请注明出处!
  • © 2019-2022 Zhuuu
  • PV: UV:

请我喝杯咖啡吧~

支付宝
微信