• 9、SpringMVC处理ajax请求



    【尚硅谷】SSM框架全套教程-讲师:杨博超

    保持热爱、奔赴山河

    9、SpringMVC处理ajax请求

    9.1 准备工作

    1 构建项目

    1 创建maven工程。
    2 将打包方式改为war。
    3 进入模块设置,创建web.xml。
    4 在web.xml添加CharacterEncodingFilterHiddenHttpMethodFilter过滤器,DispatcherServletServlet。
    5 创建包结构。
    6 创建springmvc配置文件,设置自动扫包Thymeleaf视图解析器首页视图控制器开启mvc的注解驱动 配置默认的Servlet处理静态资源
    7 创建templates文件夹,创建index.html文件。
    8 将项目添加到Tomcat中,运行并访问首页。

    2 使用axios(没有使用jQuery也可)

    axios中文网

    方式一

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>首页title>
    head>
    <body>
    <div id="app">
        <h1>index.htmlh1>
        <input type="button" value="测试SpringMVC处理ajax" @click="testAjax()">
    div>
    <script type="text/javascript" th:src="@{/static/js/vue.js}">script>
    <script type="text/javascript" th:src="@{/static/js/axios.min.js}">script>
    <script type="text/javascript">
        var vue = new Vue({
            // el挂在容器,data模型数据(没有可以不设置),methods为当前事件绑定的函数
            el: "#app",
            methods: {
                testAjax() {
                    /**
                     * axios({
                     *     url: "",         // 请求路径
                     *     method: "",      // 请求方式
                     *     param: {},       // 请求参数:name=value&name=value(无论get、post都会被拼接到请求地址后,使用request.getParameter()获取请求参数)
                     *     data: {}         // 请求参数:json发送请求参数(请求参数会被保存到请求报文的请求体中传输到服务器,使用SpringMVC获取)
                     * // then():ajax处理成功之后,处理服务器响应回来的结果
                     * }).then(response=>{  //括号内写的是箭头函数,
                     * 			// 对服务器响应数据具体的处理
                     * 			// 在浏览器控制台打印服务器响应数据
                     *     console.log(response.data);
                     * });
                     */
                }
            }
        });
    script>
    body>
    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
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38

    方式二

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>首页title>
    head>
    <body>
    <div id="app">
        <h1>index.htmlh1>
        <input type="button" value="测试SpringMVC处理ajax" @click="testAjax()">
    div>
    <script type="text/javascript" th:src="@{/static/js/vue.js}">script>
    <script type="text/javascript" th:src="@{/static/js/axios.min.js}">script>
    <script type="text/javascript">
        let vue = new Vue({
            el: "#app",
            methods: {
                testAjax() {
                    axios.post(
                        "/springmvc/test/ajax?id=1001",
                        {username: "admin", password: "123456"}
                    ).then(response => {
                        console.log(response.data);
                    });
                }
            }
        });
    script>
    body>
    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

    3 TestAjaxController

    @Controller
    public class TestAjaxController {
    
        @RequestMapping("/test/ajax")
        public void testAjax(Integer id, HttpServletResponse response) throws IOException {
            System.out.println("id" + id);
            response.getWriter().write("hello,ajax");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    9.2、@RequestBody

    1 介绍

    @RequestBody可以获取请求体信息,使用@RequestBody注解标识控制器方法的形参,当前请求的请求体就会为当前注解所标识的形参赋值。

    2 演示

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>首页title>
    head>
    <body>
    <div id="app">
        <h1>index.htmlh1>
        <input type="button" value="测试SpringMVC处理ajax" @click="testAjax()">
        <input type="button" value="测试@RequestBody注解处理json格式的请求参数" @click="testRequestBodyAjax()">
    div>
    <script type="text/javascript" th:src="@{/static/js/vue.js}">script>
    <script type="text/javascript" th:src="@{/static/js/axios.min.js}">script>
    <script type="text/javascript">
        let vue = new Vue({
            el: "#app",
            methods: {
                testAjax() {
                    axios.post(
                        "/springmvc/test/ajax?id=1001",
                        {username: "admin", password: "123456"}
                    ).then(response => {
                        console.log(response.data);
                    });
                }, testRequestBodyAjax() {
                    axios.post(
                        "/springmvc/test/request/body?id=1001",
                        {username: "admin", password: "123456"}
                    ).then(response => {
                        console.log(response.data);
                    });
                }
    
            }
        });
    script>
    body>
    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
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    @RequestMapping("/test/request/body")
    public void testRequestBody(@RequestBody String username, HttpServletResponse response) throws IOException {
        response.getWriter().write("RequestBody:" + username);
    }
    
    • 1
    • 2
    • 3
    • 4

    3 输出结果

    RequestBody:{"username":"admin","password":"123456"}
    
    • 1

    9.3、@RequestBody获取json格式的请求参数

    1 介绍

    在使用了axios发送ajax请求之后,浏览器发送到服务器的请求参数有两种格式:

    • name=value&name=value…,此时的请求参数可以通过request.getParameter()获取,对应SpringMVC中,可以直接通过控制器方法的形参获取此类请求参数。
    • {key:value,key:value,…},此时无法通过request.getParameter()获取,之前我们使用操作json的相关jar包gson或jackson处理此类请求参数,可以将其转换为指定的实体类对象或map集合。

    在SpringMVC中,直接使用@RequestBody注解标识控制器方法的形参即可将json格式转换为java对象。

    2 导入jackson的依赖

    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-databindartifactId>
        <version>2.12.1version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3 SpringMVC的配置文件中开启mvc的注解驱动

    
    <mvc:annotation-driven />
    
    • 1
    • 2

    4 @RequestBody注解标识形参

    在控制器方法的形参位置,设置json格式的请求参数要转换成的java类型(实体类或map)的参数,并使用@RequestBody注解标识。

    创建User实体类

    public class User {
        private Integer id;
        private String username;
        private String password;
        private Integer age;
        private String gender;
    
    		// 构造方法
    		// set/get方法
    		// toString方法
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    <div id="app">
        <input type="button" value="测试@RequestBody注解处理json格式的请求参数转实体类" @click="testRequestBodyUserAjax()">
    div>
    <script type="text/javascript" th:src="@{/static/js/vue.js}">script>
    <script type="text/javascript" th:src="@{/static/js/axios.min.js}">script>
    <script type="text/javascript">
        var vue = new Vue({
            el: "#app",
            methods: {
                testRequestBodyUserAjax() {
                    axios.post(
                        "/springmvc/test/request/body/map?id=1001",
                        {username: "admin", password: "123456", age:12, gender:"女"}
                    ).then(response => {
                        console.log(response.data);
                    });
                }
            }
        });
    script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    //将json格式的数据转换为实体类对象
    @RequestMapping("/test/request/body/user")
    public void testRequestBodyUser(@RequestBody User user, HttpServletResponse response) throws IOException {
        System.out.println(user);
        response.getWriter().write(user.toString());
    }
    
    //将json格式的数据转换为map集合
    @RequestMapping("/test/request/body/map")
    public void testRequestBodyMap(@RequestBody Map<String, Object> map, HttpServletResponse response) throws IOException {
        System.out.println(map);
        response.getWriter().write("成功");
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    9.4、@ResponseBody

    @ResponseBody用于标识一个控制器方法,可以将该方法的返回值直接作为响应报文的响应体响应到
    浏览器

    @RequestMapping("/test/response/body")
    public String testResponseBody(){
    	//此时会跳转到逻辑视图success所对应的页面
    	return "success";
    }
    
    @RequestMapping("/test/response/body")
    @ResponseBody
    public String testResponseBody(){
    	//此时响应浏览器数据success
    	return "success";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    9.5、@ResponseBody响应浏览器json数据

    1 介绍

    服务器处理ajax请求之后,大多数情况都需要向浏览器响应一个java对象,此时必须将java对象转换为json字符串才可以响应到浏览器,之前我们使用操作json数据的jar包gson或jackson将java对象转换为json字符串。

    在SpringMVC中,我们可以直接使用@ResponseBody注解实现此功能。

    2 导入jackson的依赖

    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-databindartifactId>
        <version>2.12.1version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    3 SpringMVC的配置文件中设置开启mvc的注解驱动

    
    <mvc:annotation-driven />
    
    • 1
    • 2

    3 使用@ResponseBody注解

    使用@ResponseBody注解标识控制器方法,在方法中,将需要转换为json字符串并响应到浏览器的java对象作为控制器方法的返回值,此时SpringMVC就可以将此对象直接转换为json字符串并响应到浏览器。

    页面

    DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>首页title>
    head>
    <body>
    <div id="app">
        <h1>index.htmlh1>
        <input type="button" value="测试SpringMVC处理ajax" @click="testAjax()"><br/>
        <input type="button" value="测试@RequestBody注解处理json格式的请求参数" @click="testRequestBodyAjax()"><br/>
        <input type="button" value="测试@RequestBody注解处理json格式的请求参数转实体类"
               @click="testRequestBodyUserAjax()"><br/>
        <input type="button" value="测试@ResponseBody注解响应json格式的数据" @click="testResponseBodyAjax()"><br/>
    div>
    <script type="text/javascript" th:src="@{/static/js/vue.js}">script>
    <script type="text/javascript" th:src="@{/static/js/axios.min.js}">script>
    <script type="text/javascript">
        let vue = new Vue({
            el: "#app",
            methods: {
                testAjax() {
                    axios.post(
                        "/springmvc/test/ajax?id=1001",
                        {username: "admin", password: "123456"}
                    ).then(response => {
                        console.log(response.data);
                    });
                }, testRequestBodyAjax() {
                    axios.post(
                        "/springmvc/test/request/body?id=1001",
                        {username: "admin", password: "123456"}
                    ).then(response => {
                        console.log(response.data);
                    });
                }, testRequestBodyUserAjax() {
                    axios.post(
                        "/springmvc/test/request/body/user?id=1001",
                        {username: "admin", password: "123456", age: 12, gender: "女"}
                    ).then(response => {
                        console.log(response.data);
                    });
                }, testResponseBodyAjax() {
                    axios.post(
                        "/springmvc/test/response/body/json"
                    ).then(response => {
                        console.log(response.data);
                    });
                }
            }
        });
    script>
    body>
    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
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54

    TestAjaxController

    // 响应浏览器实体类--->json对象
    @RequestMapping("/test/response/body/json")
    @ResponseBody
    public User testResponseBadyJson() {
        return new User(1001, "张三", "123", 23, "男");
    }
    
    
    //响应浏览器list集合--->json数组
    @RequestMapping("/test/response/body/list")
    @ResponseBody
    public List<User> testRequestBody() {
        User user1 = new User("admin1", 123);
        User user2 = new User("admin2", 123);
        User user3 = new User("admin3", 123);
        User user4 = new User("admin4", 123);
        User user5 = new User("admin5", 123);
        User user6 = new User("admin6", 123);
        List<User> list = Arrays.asList(user1, user2, user3, user4, user5, user6);
        return list;
    }
    
    //响应浏览器map集合--->json对象
    @RequestMapping("/test/response/body/map")
    @ResponseBody
    public Map<String, Object> testRequestBody() {
        User user1 = new User("admin1", 123);
        User user2 = new User("admin2", 123);
        User user3 = new User("admin3", 123);
        User user4 = new User("admin4", 123);
        User user5 = new User("admin5", 123);
        User user6 = new User("admin6", 123);
        Map<String, Object> map = new HashMap<>();
        map.put("1",user1);
        map.put("2",user2);
        map.put("3",user3);
        map.put("4",user4);
        map.put("5",user5);
        map.put("6",user6);
        return map;
    }
    
    • 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

    9.6、@RestController注解

    @RestController注解是springMVC提供的一个复合注解,标识在控制器的类上,就相当于为类添加了@Controller 注解,并且为其中的每个方法添加了@ResponseBody注解

    @Target(ElementType.TYPE)
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Controller
    @ResponseBody
    public @interface RestController {
    
    	/**
    	 * The value may indicate a suggestion for a logical component name,
    	 * to be turned into a Spring bean in case of an autodetected component.
    	 * @return the suggested component name, if any (or empty String otherwise)
    	 * @since 4.0.1
    	 */
    	@AliasFor(annotation = Controller.class)
    	String value() default "";
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
  • 相关阅读:
    JUC并发编程
    如何全天候监控维护射频网络稳定运行?
    HarmonyOS Next开发学习手册——ExtensionAbility
    vue父组件向子组件传值的方法
    nginx的基本使用
    卡码网语言基础课 |判断集合成员
    Linux 字符界面切换图形界面
    链表中LinkList L与LinkList *L( & * L.elem L->elem)
    网站攻击技术,一篇打包带走!
    Python学习路线图
  • 原文地址:https://blog.csdn.net/zhao854116434/article/details/126909420