• 9 SpringMVC处理ajax请求


    9、SpringMVC处理ajax请求

    准备工作

    新建maven项目
    在这里插入图片描述
    pom.xml中加入依赖:

        <packaging>warpackaging>
    
        <dependencies>
            
            <dependency>
                <groupId>org.springframeworkgroupId>
                <artifactId>spring-webmvcartifactId>
                <version>5.3.1version>
            dependency>
            
            <dependency>
                <groupId>ch.qos.logbackgroupId>
                <artifactId>logback-classicartifactId>
                <version>1.2.3version>
            dependency>
            
            <dependency>
                <groupId>javax.servletgroupId>
                <artifactId>javax.servlet-apiartifactId>
                <version>3.1.0version>
                <scope>providedscope>
            dependency>
            
            <dependency>
                <groupId>org.thymeleafgroupId>
                <artifactId>thymeleaf-spring5artifactId>
                <version>3.0.12.RELEASEversion>
            dependency>
        dependencies>
    
    • 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

    web.xml中配置:

        
        <filter>
            <filter-name>CharacterEncodingFilterfilter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
            <init-param>
                <param-name>encodingparam-name>
                <param-value>UTF-8param-value>
            init-param>
            <init-param>
                <param-name>forceEncodingparam-name>
                <param-value>trueparam-value>
            init-param>
        filter>
        <filter-mapping>
            <filter-name>CharacterEncodingFilterfilter-name>
            <url-pattern>/url-pattern>
        filter-mapping>
    
        
        <filter>
            <filter-name>HiddenHttpMethodFilterfilter-name>
            <filter-class>org.springframework.web.filter.HiddenHttpMethodFilterfilter-class>
        filter>
        <filter-mapping>
            <filter-name>HiddenHttpMethodFilterfilter-name>
            <url-pattern>/*url-pattern>
        filter-mapping>
    
        
        <servlet>
            <servlet-name>SpringMVCservlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
            <init-param>
                <param-name>contextConfigLocationparam-name>
                <param-value>classpath:springmvc.xmlparam-value>
            init-param>
            <load-on-startup>1load-on-startup>
        servlet>
        <servlet-mapping>
            <servlet-name>SpringMVCservlet-name>
            <url-pattern>/url-pattern>
        servlet-mapping>
    
    • 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

    导入static文件
    配置tomcat
    配置springmvc.xml

     
        <context:component-scan base-package="com.gao.controller"/>
        
        <bean id="viewResolver"
              class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
            <property name="order" value="1"/>
            <property name="characterEncoding" value="UTF-8"/>
            <property name="templateEngine">
                <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
                    <property name="templateResolver">
                        <bean
                                class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
                            
                            <property name="prefix" value="/WEB-INF/templates/"/>
                            
                            <property name="suffix" value=".html"/>
                            <property name="templateMode" value="HTML5"/>
                            <property name="characterEncoding" value="UTF-8"/>
                        bean>
                    property>
                bean>
            property>
        bean>
    
        
        <mvc:view-controller path="/" view-name="index">mvc:view-controller>
    
    
        
        <mvc:default-servlet-handler/>
        
        <mvc:annotation-driven>
            <mvc:message-converters>
                
                <bean
                        class="org.springframework.http.converter.StringHttpMessageConverter">
                    <property name="defaultCharset" value="UTF-8"/>
                    <property name="supportedMediaTypes">
                        <list>
                            <value>text/htmlvalue>
                            <value>application/jsonvalue>
                        list>
                    property>
                bean>
            mvc:message-converters>
        mvc:annotation-driven>
    
    • 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
    • 55
    • 56

    回顾axios

    http://axios-js.com/

        /*
        *  axios({
              url:"",//请求路径
              method: "",//请求方式
              params:{},//以name=value&name=value的方式发送请求参数
              //不管使用的请求方式是get还是post,请求参数都会拼接到请求地址后
              //此种方式的请求参数可以通过request.getParameter()获取
               data:{},//以json格式发送的请求参数
               //请求参数会被保存到请求报文的请求体传输到服务器
               //此种方式的请求参数不可以通过request.getParameter()获取
            }).then(response=>{
                console.log(response.data);
           });
        * */
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    在这里插入图片描述

    测试SpringMVC处理Ajax请求

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>indextitle>
    head>
    <body>
    <div id="app">
        <h1>index.htmlh1>
        <input type="button" value="测试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">
        /*
        *  axios({
              url:"",//请求路径
              method: "",//请求方式
              params:{},//以name=value&name=value的方式发送请求参数
              //不管使用的请求方式是get还是post,请求参数都会拼接到请求地址后
              //此种方式的请求参数可以通过request.getParameter()获取
               data:{},//以json格式发送的请求参数
               //请求参数会被保存到请求报文的请求体传输到服务器
               //此种方式的请求参数不可以通过request.getParameter()获取
            }).then(response=>{
                console.log(response.data);
           });
        * */
    
        var vue = new Vue({
            el:"#app",
            methods:{
                testAjax(){
    
                    axios.post(
                        "/springmvc/test/ajax?id=1001",
                        {username:"admin",password:"1234546"}
                    ).then(response=>{
                        console.log(response.data);
                    })
                    // axios({
                    //     url:"",
                    //     method: "",
                    //     params:{},
                    //     data:{}
                    // }).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
    • 55
    • 56
    • 57
        @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

    9.1、@RequestBody

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

    
    <form th:action="@{/test/RequestBody}" method="post">
    用户名:<input type="text" name="username"><br>
    密码:<input type="password" name="password"><br>
    <input type="submit">
    form>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    @RequestMapping("/test/RequestBody")
    public String testRequestBody(@RequestBody String requestBody){
    System.out.println("requestBody:"+requestBody);
    return "success";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    输出结果
    requestBody:username=admin&password=123456

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

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

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

    使用@RequestBody获取json格式的请求参数的条件

    1. 导入jackson的依赖
    <dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-databindartifactId>
    <version>2.12.1version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    2. SpringMVC的配置文件中设置开启mvc的注解驱动
    
    <mvc:annotation-driven />
    
    • 1
    • 2
    3. 在控制器方法的形参位置,设置json格式的请求参数要转换成的java类型(实体类或map)的参数,并使用@RequestBody注解标识
    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>indextitle>
    head>
    <body>
    <div id="app">
        <h1>index.htmlh1>
        <input type="button" value="测试ajax" @click="testAjax()">
        <input type="button" value="@ResquestBody测试ajax" @click="testResquestBody()">
    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">
        /*
        *  axios({
              url:"",//请求路径
              method: "",//请求方式
              params:{},//以name=value&name=value的方式发送请求参数
              //不管使用的请求方式是get还是post,请求参数都会拼接到请求地址后
              //此种方式的请求参数可以通过request.getParameter()获取
               data:{},//以json格式发送的请求参数
               //请求参数会被保存到请求报文的请求体传输到服务器
               //此种方式的请求参数不可以通过request.getParameter()获取
            }).then(response=>{
                console.log(response.data);
           });
        * */
    
        var vue = new Vue({
            el:"#app",
            methods:{
                testAjax(){
    
                    axios.post(
                        "/springmvc/test/ajax?id=1001",
                        {username:"admin",password:"1234546"}
                    ).then(response=>{
                        console.log(response.data);
                    });
                    // axios({
                    //     url:"",
                    //     method: "",
                    //     params:{},
                    //     data:{}
                    // }).then(response=>{
                    //     console.log(response.data);
                    // });
                },
                testResquestBody(){
                    axios.post(
                        "/springmvc/test/RequestBody/json",
                    {username:"admin",password:"1234546",age:23,gender:"男"}
                    ).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
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66

    User类

    package com.gao.pojo;
    
    /**
     * @Projectname SSM
     * @Filename User
     * @Author an
     * @Data 2022/8/6 9:21
     * @Description TODO
     */
    public class User {
    
        private Integer id;
    
        private String username;
    
        private String password;
    
        private Integer age;
    
        private String gender;
    
        public User(Integer id, String username, String password, Integer age, String gender) {
            this.id = id;
            this.username = username;
            this.password = password;
            this.age = age;
            this.gender = gender;
        }
    
        public User() {
        }
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer id) {
            this.id = id;
        }
    
        public String getUsername() {
            return username;
        }
    
        public void setUsername(String username) {
            this.username = username;
        }
    
        public String getPassword() {
            return password;
        }
    
        public void setPassword(String password) {
            this.password = password;
        }
    
        public Integer getAge() {
            return age;
        }
    
        public void setAge(Integer age) {
            this.age = age;
        }
    
        public String getGender() {
            return gender;
        }
    
        public void setGender(String gender) {
            this.gender = gender;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", username='" + username + '\'' +
                    ", password='" + password + '\'' +
                    ", age=" + age +
                    ", gender='" + gender + '\'' +
                    '}';
        }
    }
    
    
    • 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
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
        @RequestMapping("/test/ajax")
        public void testajax(Integer id, @RequestBody Map<String,Object> map, HttpServletResponse response) throws IOException {
            System.out.println("id:"+id);
            System.out.println(map);
    //        System.out.println("requestBody:"+requestBody);
            response.getWriter().write("hello,ajax");
        }
    
        @RequestMapping("/test/RequestBody/json")
        public void testRequestBody(@RequestBody User user,HttpServletResponse response) throws IOException {
            System.out.println(user);
            response.getWriter().write("hello,RequestBody");
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    输出结果:
    User{id=null, username=‘admin’, password=‘1234546’, age=23, gender=‘男’}


    9.3、@ResponseBody

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

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

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

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

    @ResponseBody响应浏览器json数据的条件:

    1、导入jackson的依赖
    <dependency>
    <groupId>com.fasterxml.jackson.coregroupId>
    <artifactId>jackson-databindartifactId>
    <version>2.12.1version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    2、SpringMVC的配置文件中设置开启mvc的注解驱动
    
    <mvc:annotation-driven />
    
    • 1
    • 2
    3、使用@ResponseBody注解标识控制器方法,在方法中,将需要转换为json字符串并响应到浏览器的java对象作为控制器方法的返回值,此时SpringMVC就可以将此对象直接转换为json字符串并响应到浏览器
    <input type="button" value="测试@ResponseBody响应浏览器json格式的数据"
    @click="testResponseBody()"><br>
    <script type="text/javascript" th:src="@{/js/vue.js}">script>
    <input type="button" value="测试@ResponseBody响应浏览器json格式的数据"
    @click="testResponseBody()"><br>
    <script type="text/javascript" th:src="@{/js/vue.js}">script>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    //响应浏览器list集合
    @RequestMapping("/test/ResponseBody/json")
    @ResponseBody
    public List<User> testResponseBody(){
    User user1 = new User(1001,"admin1","123456",23,"男");
    User user2 = new User(1002,"admin2","123456",23,"男");
    User user3 = new User(1003,"admin3","123456",23,"男");
    List<User> list = Arrays.asList(user1, user2, user3);
    return list;
    }
    //响应浏览器map集合
    @RequestMapping("/test/ResponseBody/json")
    @ResponseBody
    public Map<String, Object> testResponseBody(){
    User user1 = new User(1001,"admin1","123456",23,"男");
    User user2 = new User(1002,"admin2","123456",23,"男");
    User user3 = new User(1003,"admin3","123456",23,"男");
    Map<String, Object> map = new HashMap<>();
    map.put("1001", user1);
    map.put("1002", user2);
    map.put("1003", user3);
    return map;
    }
    //响应浏览器实体类对象
    @RequestMapping("/test/ResponseBody/json")
    @ResponseBody
    public User testResponseBody(){
    return user;
    }
    
    • 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

    9.5、@RestController注解

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

  • 相关阅读:
    算法:只使用一个int类型变量表示日期
    基于Java web的电动车销售平台 毕业设计-附源码201524
    【Golang之路】——slice总结
    C++ AB组辅导课
    基于PHP+MySQL企业网络推广平台系统的设计与实现
    一文读懂 TsFile
    【老生谈算法】matlab实现LU分解算法源码——LU算法
    农产品溯源中GIS应用
    地道解释优化领域下什么是多目标、多峰、多模态、动态、噪声环境和超多目标优化问题
    N32学习笔记1-工程模板建立
  • 原文地址:https://blog.csdn.net/qq_44774198/article/details/126183276