初学SpringMVC之 Ajax 篇

Ajax(Asynchronous JavaScript and XML)是一种在无需重新加载整个网页,能够更新部分网页的技术

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

使用 Ajax 技术的网页,通过在后台服务器进行少量的数据交换,就可以实现异步局部更新

pom.xml:

XML 复制代码
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.2.0.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.1</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.34</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.17.2</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>2.0.51</version>
    </dependency>

web.xml:

XML 复制代码
<?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"
         metadata-complete="true">

  <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>

applicationContext.xml:

XML 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
    <context:component-scan base-package="com.demo.controller"/>

    <!-- 让SpringMVC不处理静态资源 -->
    <mvc:default-servlet-handler/>

    <!--    &lt;!&ndash; 支持MVC注解驱动 &ndash;&gt;-->
    <!--    <mvc:annotation-driven/>-->

    <!-- 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>

text.html:

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title></title>
    <script>
        function go(){
            var url = document.getElementById("url").value;
            document.getElementById("iframe").src = url;
        }
    </script>
</head>
<body>
<div>
    <p>输入地址:</p>
    <p>
        <input type="text" id="url" value="https://www.4399.com/"/>
        <input type="button" value="提交" onclick="go()"/>
    </p>
</div>

<div>
    <iframe id="iframe" style="width: 100%;height: 500px"></iframe>
</div>
</body>
</html>

效果如下:

(上述仅实现类似异步的模样,局部改变)

官网下载 jquery,放到 js 目录下

AjaxController.java:

java 复制代码
package com.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class AjaxController {
    @RequestMapping("/ajax")
    public void test(String name, HttpServletResponse response) throws IOException {
        System.out.println(name);
        if("张三".equals(name)){
            response.getWriter().println("true");
        }else {
            response.getWriter().println("false");
        }
    }
}

index.jsp:

html 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
        <script>
            function a(){
                $.post({
                    url:"${pageContext.request.contextPath}/ajax",
                    data:{"name":$("#username").val()},
                    success:function(data){
                        alert(data);
                    }
                })
            }
        </script>
    </head>
<body>
用户名:<input type="text" id="username" onblur="a()">
</body>
</html>

效果如下:

XMLHttpRequest(简称 xhr),是浏览器提供的 JS 对象,通过它可以请求到服务器上的数据资源

xhr 允许进行异步请求,它可以在后台执行,而不会阻止页面的其他操作

Ajax 异步加载数据:

User.java:

java 复制代码
package com.demo.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private String name;
    private int age;
}

AjaxController.java:

java 复制代码
package com.demo.controller;

import com.demo.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class AjaxController {
    @RequestMapping("/list")
    public List<User> list(){
        List<User> arrayList = new ArrayList<User>();

        //添加数据
        arrayList.add(new User("张三1",3));
        arrayList.add(new User("张三2",3));

        return arrayList;
    }
}

list.jsp:

html 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
		<script>
			$(function(){
				$("#btn").click(function(){
					$.post("${pageContext.request.contextPath}/list",function (data){
						//console.log(data);
						var html="";
						for(let i = 0;i < data.length;i++){
						    html += "<tr>" +
						        "<td>" + data[i].name + "</td>" +
						        "<td>" + data[i].age + "</td>" +
						        "</tr>"
						}
						$("#content").html(html);
					})
				})
			});
		</script>
	</head>
	<body>
		<input type="button" value="加载数据" id="btn"/>
		<table>
			<tr>
				<td>姓名</td>
				<td>年龄</td>
			</tr>
			<tbody id="content"></tbody>
		</table>
	</body>
</html>

效果如下:

Ajax 验证用户名:

login.jsp:

html 复制代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script src="${pageContext.request.contextPath}/statics/js/jquery-3.5.1.js"></script>
		<script>
			function a1(){
                $.post({
                    url:"${pageContext.request.contextPath}/login",
                    data:{"name":$("#name").val()},
                    success:function(data){
                        console.log(data);
                    }
                })
			}
			function a2(){
                $.post({
                    url:"${pageContext.request.contextPath}/login",
                    data:{"pwd":$("#pwd").val()},
                    success:function(data){
                        console.log(data);
                    }
                })
			}
		</script>
	</head>
	<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>
</html>

AjaxController.java:

java 复制代码
package com.demo.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class AjaxController {
    @RequestMapping("/login")
    public String login(String name,String pwd) {
        String msg = "";
        if (name != null) {
            if ("admin".equals(name)) {
                msg = "true";
            } else {
                msg = "用户名错误";
            }
        }
        if(pwd != null){
            if("123".equals(pwd)){
                msg = "true";
            } else {
                msg = "密码错误";
            }
        }
        return msg;
    }
}

效果如下:

相关推荐
nameofworld19 分钟前
前端面试笔试(二)
前端·javascript·面试·学习方法·数组去重
hummhumm1 小时前
第 12 章 - Go语言 方法
java·开发语言·javascript·后端·python·sql·golang
hummhumm1 小时前
第 8 章 - Go语言 数组与切片
java·开发语言·javascript·python·sql·golang·database
尼克_张1 小时前
tomcat配合geoserver安装及使用
java·tomcat
wywcool1 小时前
JVM学习之路(5)垃圾回收
java·jvm·后端·学习
-seventy-2 小时前
Java Web 工程全貌
java
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ2 小时前
idea 删除本地分支后,弹窗 delete tracked brank
java·ide·intellij-idea
言慢行善2 小时前
idea出现的问题
java·ide·intellij-idea
杨荧2 小时前
【JAVA毕业设计】基于Vue和SpringBoot的宠物咖啡馆平台
java·开发语言·jvm·vue.js·spring boot·spring cloud·开源
zhanghaisong_20152 小时前
Caused by: org.attoparser.ParseException:
前端·javascript·html·thymeleaf