SpringMVC如何返回JSON数据

2025-10-04 13:33:27

1、在index.jsp首页添加一个返回JSON的超链接。

<html>

<script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script>

<script type="text/javascript">

        $(function(){

                $("#testJson").click(function(){

                        var url = this.href;

                        

                        var args = {};

                        

                        $.post(url,args,function(data) {

                                for(var i=0;i<data.length;i++) {

                                        var id = data[i].id;

                                        var lastName = data[i].lastName;

                                        

                                        alert(id+":" + lastName);

                                }

                                

                        });

                });

        })

</script>

<body>

        <h2>

                <a href="springmvc/testJson" id="testJson">Test JSON</a>

        </h2>

</body>

SpringMVC如何返回JSON数据

2、在SpringMVC控制层返回JSON数据。

package com.gwolf.springmvc.handlers;

import java.util.Collection;

import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.validation.BindingResult;

import org.springframework.validation.FieldError;

import org.springframework.web.bind.annotation.ModelAttribute;

import org.springframework.web.bind.annotation.PathVariable;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;

import com.gwolf.springmvc.dao.DepartmentDao;

import com.gwolf.springmvc.dao.EmployeeDao;

import com.gwolf.springmvc.domain.Employee;

@Controller

public class EmployeeHandler {

        @Autowired

        private EmployeeDao employeeDao;

        

        @Autowired

        private DepartmentDao departmentDao;

        

        @RequestMapping("/springmvc/testJson")

        @ResponseBody

        public Collection<Employee> testJson() {

                return this.employeeDao.getAll();

        }

        

        

        

}

SpringMVC如何返回JSON数据

3、在pom.xml配置文件中加入跟SpringMVC返回JSON数据绑定相关的依赖包:

<dependency>

    <groupId>com.fasterxml.jackson.core</groupId>

    <artifactId>jackson-databind</artifactId>

    <version>2.8.8</version>

</dependency>

SpringMVC如何返回JSON数据

4、运行tomcat,查看json数据是否调用成功。

SpringMVC如何返回JSON数据

5、我们打开谷歌开发者工具栏,查看JSON数据的返回情况。

SpringMVC如何返回JSON数据

6、在开发者工具栏查看json数据的结果。

SpringMVC如何返回JSON数据

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢