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;
        }

    前端输出结果:

  • 相关阅读:
    在Linux系统中Navicat for MySQL 出现1045错误如何处理
    一个老程序员这些年的心得体会
    忘了
    DAY11
    day10_plus
    day10
    东北育才冲刺noip(day9)
    Java语言Socket接口用法详解
    JDBC-ODBC桥连接方式操纵SQL数据库
    JDBC连接SQL Server 2005步骤详解
  • 原文地址:https://www.cnblogs.com/to-red/p/11348506.html
Copyright © 2011-2022 走看看