• 1)添加jackson依赖
  • 2)在webapp目录下新建js目录,添加jQuery函数库
  • 3)在index.jsp页面上导入函数库
  • 4)在action上添加注解ResponseBody,用来处理ajax请求
  • 5)在springmvc.xml文件中添加注解驱动<mvc:annotationdriven>,它用来解析@ResponseBody注解

搭建项目

new ->Project/Module->Maven->勾选Create from archetype->maven-archetype-webapp模板->包名/项目名

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <groupId>com.chentianyu</groupId>
  6. <artifactId>springmvc_003_ajax</artifactId>
  7. <version>1.0-SNAPSHOT</version>
  8. <packaging>war</packaging>
  9. <properties>
  10. <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  11. <maven.compiler.source>1.8</maven.compiler.source>
  12. <maven.compiler.target>1.8</maven.compiler.target>
  13. </properties>
  14. <dependencies>
  15. <dependency>
  16. <groupId>junit</groupId>
  17. <artifactId>junit</artifactId>
  18. <version>4.11</version>
  19. <scope>test</scope>
  20. </dependency>
  21. <dependency>
  22. <groupId>org.springframework</groupId>
  23. <artifactId>spring-webmvc</artifactId>
  24. <version>5.3.16</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>javax.servlet</groupId>
  28. <artifactId>javax.servlet-api</artifactId>
  29. <version>4.0.1</version>
  30. </dependency>
  31. <dependency>
  32. <groupId>com.fasterxml.jackson.core</groupId>
  33. <artifactId>jackson-databind</artifactId>
  34. <version>2.13.1</version>
  35. </dependency>
  36. </dependencies>
  37. <build>
  38. <resources>
  39. <resource>
  40. <directory>src/main/java</directory>
  41. <includes>
  42. <include>**/*.xml</include>
  43. <include>**/*.properties</include>
  44. </includes>
  45. </resource>
  46. <resource>
  47. <directory>src/main/resources</directory>
  48. <includes>
  49. <include>**/*.xml</include>
  50. <include>**/*.properties</include>
  51. </includes>
  52. </resource>
  53. </resources>
  54. </build>
  55. </project>

注册中文编码+注册springmvc框架

<?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">
    <!--添加中文编码-->
    <filter>
        <filter-name>filter1</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!--
            private String encoding;
           private boolean forceRequestEncoding = false;
           private boolean forceResponseEncoding = false;
        -->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>filter1</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--注册springmvc-->
    <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:springmvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

ajax请求返回json数组功能实现

需求是:从客户端发送一个jquery封装后的ajax请求,然后到服务器端,服务器端创建一个学生的**List**集合返回到客户端,客户端将这个集合解析出来。

在springmvc的加持下,我们发现服务器扔回来的集合回自动会被转换为json数组

jQuery下载

创建js文件夹jQuery版本.js

目录结构

webapp
|_js
|__jquery-3.6.0.js
|_WEB-INF
|__web.xml
|_index,jsp

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <%--导入jQuery的函数库--%>
    <script src="./js/jquery-3.6.0.js"></script>
</head>
<body>
    <a href="javascript:showStu()">访问服务器返回学生集合</a>
    <div id="myDiv"></div>
</body>
<script type="text/javascript">
    function showStu(){
        //使用jQuery封装的ajax()方法发送请求
        $.ajax({
            url: "${pageContext.request.contextPath}/list",
            type: "get",
            dataType: "json",
            success:function(stuList/*这个地方就是json数组*/){
                var s = "";
                $.each(stuList,function (i/*遍历出来的下标*/,stu/*遍历出来的学生对象*/){
                    s += stu.name + "---" + stu.age + "<br>";
                });
                //回显数据
                $("#myDiv").html(s);
            }
        });
    }
</script>
</html>

既然有学生的封装就有学生的

实体类
package com.chentianyu.pojo;

public class Student {
    private String name;//必须叫name和age,因为我们在页面上操作这个对象的时候我们就在用name和age的属性
    private int age;

    public Student() {
    }

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

    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 "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

注意: 在当前的index.jsp页面上stu.name调用的其实是实体类中的getName和getAge

Controller开发
package com.chentianyu.controller;

import com.chentianyu.pojo.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

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

@Controller
public class StuListAction {
    @ResponseBody   //用来解析ajax请求,必须在springmvc.xml文件中添加注解驱动
    @RequestMapping("/list")
    public List<Student> list(){
        List<Student> list = new ArrayList<>();
        Student stu1 = new Student("张三",23);
        Student stu2 = new Student("李四",24);
        Student stu3 = new Student("王五",25);

        list.add(stu1);
        list.add(stu2);
        list.add(stu3);

        return list;//springmvc框架负责将集合转为json数组
    }
}

添加#ResponseBody的注解驱动

<?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">
    <!--包扫描-->
    <context:component-scan base-package="com.chentianyu.controller" />
    <!--不用添加视图解析器,因为处理的是ajax请求-->
    <!--必须要添加注解驱动,专门用来处理ajax请求-->
    <mvc:annotation-driven />
</beans>

添加tomcat

出现org.springframework.web.servlet.DispatcherServlet.noHandlerFound No mapping for GET [/uri]就添加<mvc:default-servlet-handler />:

<?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">
    <!--包扫描-->
    <context:component-scan base-package="com.chentianyu.controller" />
    <!--不用添加视图解析器,因为处理的是ajax请求-->
    <!--必须要添加注解驱动,专门用来处理ajax请求-->
    <mvc:annotation-driven />
    <mvc:default-servlet-handler />
</beans>

出现张三李四效果,就等于开发完毕

image.png