天天看点

使用SpringMVC实现JSON数据的传输

一、导入jar包

1.jackson-annotations-2.1.5.jar

2.jackson-core-2.1.5.jar

3.jackson-databind-2.1.5.jar

4.commons-logging-1.1.1.jar

5.spring-aop-4.0.0.RELEASE.jar

6.spring-beans-4.0.0.RELEASE.jar

7.spring-context-4.0.0.RELEASE.jar

8.spring-core-4.0.0.RELEASE.jar

9.spring-expression-4.0.0.RELEASE.jar

10.spring-web-4.0.0.RELEASE.jar

11.spring-webmvc-4.0.0.RELEASE.jar

12.taglibs-standard-impl-1.2.1.jar

13.taglibs-standard-spec-1.2.1.jar

二、前端代码

注:通过AJAX方式请求

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
	$(function(){
		var $div=$("#d");
		$("a").click(function(){
			$.getJSON("getJsonObject",null,function(result){
				for(var i=0;i<result.length;i++){
					$div.append("<h2>"+result[i].id+"</h2>");
				} 
			});
			return false;
		});
	});
</script>
</head>
<body>
	<div align="center">
		<a href="getJsonObject" target="_blank" rel="external nofollow" >获取Json对象</a>
	</div>
	<div align="center" id="d"></div>
</body>
</html>
           

三、后端代码

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.atguigu.dao.EmployeeDao;
import com.atguigu.entity.Employee;

@Controller
public class JsonController {
	
	@Autowired
	private EmployeeDao employeeDao;
	
	//@ResponseBody该注解作用告诉服务器响应的不是页面,而是JSON格式的文件资源
	@ResponseBody
	@RequestMapping(value="/getJsonObject")
	public Object getJsonObject() {
		Collection<Employee> allEmployee = employeeDao.getAll();
		return allEmployee;
	}
}

           

四、运行结果

使用SpringMVC实现JSON数据的传输