【Spring】SpringMVC 使用 Ajax

1. 简介

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

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

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

  • Google Suggest 使用 Ajax 创造出动态性极强的 Web 界面:当您在谷歌的搜索框输入关键字时,JavaScript 会把这些字符发送到服务器,然后服务器会返回一个搜索建议的列表。

  • 传统的网页(即不用ajax技术的网页),想要更新内容或者提交一个表单,都需要重新加载整个网页。

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

  • 使用 Ajax,用户可以创建接近本地桌面应用的直接、高可用、更丰富、更动态的 Web 用户界面。

示例项目的完整代码见https://codechina.csdn.net/dreaming_coder/springmvc-ajax

2. jQuery 实现 Ajax

纯 JavaScript 的实现比较繁琐,直接使用 jQuery 提供的,方便学习和使用,避免重复造轮子

Ajax 的核心是 XMLHttpRequest 对象(XHR)。XHR为向服务器发送请求和解析服务器响应提供了接口。能够以异步方式从服务器获取新数据。

jQuery 提供多个与 Ajax 有关的方法。

通过 jQuery Ajax 方法,您能够使用 HTTP Get 和 HTTP Post 从远程服务器上请求文本、HTML、XML 或 JSON – 同时您能够把这些外部数据直接载入网页的被选元素中。

jQuery.get(...)
      所有参数:
            url: 待载入页面的 url 地址
           data: 待发送的键值对参数
        success: 成功时的回调函数
       dataType: 返回内容格式,xml, json, script, text, html
jQuery.post(...)
      所有参数:
            url: 待载入页面的 url 地址
           data: 待发送的键值对参数
        success: 成功时的回调函数
       dataType: 返回内容格式,xml, json, script, text, html
jQuery.ajax(...)
      部分参数:
             url: 请求地址
          method: 请求方式,GET、POST等
         headers: 请求头
            data: 要发送的数据
     contentType: 即将发送信息至服务器的内容编码类型(默认: "application/x-www-form-urlencoded; charset=UTF-8")
           async: 是否异步
         timeout: 设置请求超时时间(毫秒)
      beforeSend: 发送请求前执行的函数(全局)
        complete: 完成之后执行的回调函数(全局)
         success: 成功之后执行的回调函数(全局)
           error: 失败之后执行的回调函数(全局)
         accepts: 通过请求头发送给服务器,告诉服务器当前客户端可接受的数据类型
        dataType: 将服务器端返回的数据转换成指定类型
                   "xml": 将服务器端返回的内容转换成xml格式
                  "text": 将服务器端返回的内容转换成普通文本格式
                  "html": 将服务器端返回的内容转换成普通文本格式,在插入DOM中时,如果包含JavaScript标签,则会尝试去执行。
                "script": 尝试将返回值当作JavaScript去执行,然后再将服务器端返回的内容转换成普通文本格式
                  "json": 将服务器端返回的内容转换成相应的JavaScript对象
                 "jsonp": JSONP 格式使用 JSONP 形式调用函数时,如 "myurl?callback=?" jQuery 将自动替换 ? 为正确的函数名,以执行回调函数

3. 示例

3.1 环境准备

【pom.xml】

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.ice</groupId>
    <artifactId>demo</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>14</maven.compiler.source>
        <maven.compiler.target>14</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>
        <!--servlet-api导入高版本的-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.2</version>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
</project>

【web.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">

    <!--1.注册servlet-->
    <servlet>
        <servlet-name>SpringMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--通过初始化参数指定SpringMVC配置文件的位置,进行关联-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <!-- 启动顺序,数字越小,启动越早 -->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <!--所有请求都会被springmvc拦截 -->
    <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>

    <!-- 超时时间 -->
    <session-config>
        <session-timeout>15</session-timeout>
    </session-config>

</web-app>

【applicationContext.xml】

<?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 http://www.springframework.org/schema/context/spring-context.xsd
                            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- mvc注解驱动 -->
    <mvc:annotation-driven/>

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

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

    <!-- 视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          id="internalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

【User】

package com.ice.pojo;

import java.util.StringJoiner;


public class User {
    
    
    private int id;
    private String name;
    private int age;

    public User() {
    
    
    }

    public User(int id, String name, int age) {
    
    
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public int getAge() {
    
    
        return age;
    }

    public void setAge(int age) {
    
    
        this.age = age;
    }

    @Override
    public String toString() {
    
    
        return new StringJoiner(", ", User.class.getSimpleName() + "[", "]")
                .add("id=" + id)
                .add("name='" + name + "'")
                .add("age=" + age)
                .toString();
    }
}

3.2 编写控制器

【AjaxController】

package com.ice.controller;

import com.alibaba.fastjson.JSON;
import com.ice.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/ajax")
public class AjaxController {
    
    

    // 第一种方式,服务器返回字符串直接用 response
    @RequestMapping("/a1")
    public void ajax(String name, HttpServletResponse response) throws IOException {
    
    
        if ("admin".equals(name)) {
    
    
            response.getWriter().print("true");
        } else {
    
    
            response.getWriter().print("false");
        }
    }
	
    // 第二种方式,RestFul风格
    @RequestMapping(value = "/a2", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String ajax2() {
    
    
        List<User> list = new ArrayList<User>();

        User user1 = new User(1, "亚索", 18);
        User user2 = new User(2, "瑞雯", 3);
        User user3 = new User(3, "艾瑞莉娅", 13);
        User user4 = new User(4, "亚托克斯", 25);

        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);

        String s = JSON.toJSONString(list);

        return s;
    }
}

【index.jsp】

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Ajax</title>
    <%--  引入jQuery  --%>
    <script src="${pageContext.request.contextPath}/js/jquery-3.5.1.js"></script>
</head>
<body>
<%--失去焦点产生事件--%>
用户名:<input type="text" id="txtName" onblur="a1()">
</body>
<script type="text/javascript">
    function a1() {
    
    
        $.ajax({
    
    
            url: "${pageContext.request.contextPath}/ajax/a1",
            data: {
    
    "name": document.querySelector("#txtName").value},
            success: function (data, status) {
    
    
                console.log(data);
                console.log(status);
            }
        });
    }
</script>
</html>

【index2.jsp】

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="${pageContext.request.contextPath}/js/jquery-3.5.1.js"></script>

    <style>
        table {
    
    
            margin: auto;
            vertical-align: center;
            text-align: center;
            border-collapse: collapse;
        }

        table, td, th {
    
    
            border: 1px solid blue; /* 没有顺序要求 */
        }
    </style>
</head>
<body>
<input type="button" id="btn" value="获取数据"/>
<table>
    <tr>
        <th width="200px">姓名</th>
        <th width="200px">年龄</th>
    </tr>
    <tbody id="content">

    </tbody>
</table>
</body>
<script type="text/javascript">
    let btn = document.querySelector("#btn");

    function display() {
    
    
        $.ajax({
    
    
            url: "${pageContext.request.contextPath}/ajax/a2",
            success: function (data) {
    
    

                let html = "";

                for (let i = 0; i < data.length; i++) {
    
    
                    html += "<tr>" +
                        "<td>" + data[i].name + "</td>" +
                        "<td>" + data[i].age + "</td>" +
                        "</tr>";
                }

                document.querySelector("#content").innerHTML = html;
            }
        });
    }

    btn.addEventListener("click", display, false);

</script>
</html>

猜你喜欢

转载自blog.csdn.net/dreaming_coder/article/details/113729330