【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 + "\n");
                    }
                }
            );
        });
    });
</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;
    }

前端输出结果:

 

转载于:https://www.cnblogs.com/to-red/p/11348506.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值