zoukankan      html  css  js  c++  java
  • 【SpringMVC】SpringMVC通过Ajax给前端返回JSON

    在SpringMVC项目中,使用JS静态资源,需要对该静态资源的请求放行。

    只需要在springmvc.xml中配置:

        <mvc:default-servlet-handler></mvc:default-servlet-handler>

    即启用了Tomcat默认的处理Servlet,当没有在@RequestMapping中找到对应的请求路径时,会直接访问该路径的资源。

    使用JSON,还需要添加JSON相关的Jar包。jackson-databind.jar、jackson-annotations.jar、jackson-core.jar

    使用maven很简单,添加jackson-databind.jar依赖,会自动下载其余两个:

    pom.xml

            <dependency>
                <groupId>com.fasterxml.jackson.core</groupId>
                <artifactId>jackson-databind</artifactId>
                <version>2.9.9</version>
            </dependency>
    • 前端使用Jquery的$.post()
    <script src="${pageContext.request.contextPath}/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $("#testJson").click(function () {
                $.post(
                    "handler/testJson",
                    function (datas) {
                        for (let i = 0; i < datas.length; i++) {
                            console.log(datas[i].id + "
    ");
                        }
                    }
                );
            });
        });
    </script>
    <button id="testJson">testJson</button>
    • 后台使用一个学生类(Student)测试,使用注解@ResponseBody返回的不再时一个视图,不会被视图解析器解析为页面

    返回的是一个List,传统的方式需要再JS中用eval()方法,将返回的数据转化为JavaScript可以处理的数据遍历输出。再SpringMVC中,仅仅返回List,前端就可以正常的遍历输出。

        @ResponseBody
        @RequestMapping("testJson")
        public List<Student> testJson() {
            List<Student> students = new ArrayList<Student>();
            Student stu1 = new Student(1, "zs");
            Student stu2 = new Student(2, "ls");
            Student stu3 = new Student(3, "ww");
            students.add(stu1);
            students.add(stu2);
            students.add(stu3);
            return students;
        }

    前端输出结果:

  • 相关阅读:
    asp.net过滤数据中有异常数据字符串
    微信内置浏览器的 User Agent的判断
    最近突然想了很久还是开博每天写点什么
    Sonar-scanner 插件配置应用
    存clob的值
    动态代理
    在oracle函数中不可直接将变量作为sql语句中的参数
    按照行、列进行统计(按两个维度进行统计)
    查询关联不上的数据,三张表查询
    前台页面——js/jq循环
  • 原文地址:https://www.cnblogs.com/to-red/p/11348506.html
Copyright © 2011-2022 走看看