SpringMVC支持ajax

1.SpringMVC快速完成ajax请求:

1)、返回数据是json格式

2)、页面发起ajax请求,$.ajax()

2.原生JavaWeb:

1)、导入GSON包

2)、返回数据用GSON转成JSON格式

3)、写出数据

3.SpringMVC-ajax:

1)、导包

jackson-annotations-2.9.8.jar

jackson-core-2.9.8.jar

jackson-databind-2.9.8.jar

2)、返回JSON格式

java代码

/**
	 * 将返回的数据放在响应体中,
	 * 
	 * 如果是对象,jackson包自动将对象转为json
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getallajax")
	public List<Employee> ajaxGetAllEmps() {
		List<Map<String, Object>> empls = employeeService.getEmpls();
		List<Employee> emps = new LinkedList<Employee>();
		for (Map<String, Object> map : empls) {
			System.out.println(map);
			emps.add(new Employee((int) map.get("id"), (String) map.get("lastname"), (String) map.get("email"),
					(int) map.get("gender"), (int) map.get("departmentid")));
		}
		return emps;
	}

在页面发起/getallajax请求,页面数据为


使用ajax获取员工信息:@ResponseBody将返回的数据放在响应体中

jsp页面:

<%@page import="java.util.Date"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	pageContext.setAttribute("ctp", request.getContextPath());
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-3.3.1/jquery-3.3.1.min.js"></script>
</head>
<body>
<%=new Date() %>
<a href="${ctp }/getallajax">获取员工信息</a>
<div>
		
</div>
</body>
<script type="text/javascript">
	$("a:first").click(function () {
		//1.发送ajax请求获取所有员工信息
		$.ajax({
			url:"${ctp}/getallajax",
			type:"post",
			success:function(data){
				//console.log(data);
				$("div").empty();
				$.each(data,function(){
					var empinfo = this.lastName+"::"+this.email+"::"+(this.gender==0?'女':'男')+"::"+this.departmentid;
					$("div").append(empinfo+"<br/>");
				});
			}
			
		});	
		//禁用默认行为
		return false;
	});
</script>
</html>

java代码:

/**
	 * 将返回的数据放在响应体中,
	 * 
	 * 如果是对象,jackson包自动将对象转为json
	 * 
	 * @return
	 */
	@ResponseBody
	@RequestMapping("/getallajax")
	public List<Employee> ajaxGetAllEmps() {
		List<Map<String, Object>> empls = employeeService.getEmpls();
		List<Employee> emps = new LinkedList<Employee>();
		for (Map<String, Object> map : empls) {
			System.out.println(map);
			emps.add(new Employee((int) map.get("id"), (String) map.get("lastname"), (String) map.get("email"),
					(int) map.get("gender"), (int) map.get("departmentid")));
		}
		return emps;
	}

执行结果:


使用ajax发送json数据给服务器:@RequestBody可以获取请求体

jsp页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
<%
	pageContext.setAttribute("ctp", request.getContextPath());
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-3.3.1/jquery-3.3.1.min.js"></script>
</head>
<body>
<a href="${ctp }/getjson">发送json数据给服务器</a>
</body>
<script type="text/javascript">
	$("a:first").click(function () {
		//一个js对象
		var emp ={
			lastName:'asad',
			email:'123456@qq.com',
			gender:1,
			departmentid:101
		};
		//将js对象转成json数据
		var empstr = JSON.stringify(emp);
		console.log(empstr);
		$.ajax({
			url:"${ctp}/getjson",
			type:"post",
			//请求数据为json数据
			data:empstr,
			
			contentType: 'application/json;charset=utf-8',
			success:function(data){
				alert(data);
			}
		});
		return false;
	});
</script>
</html>

java代码:

	/**
	 * @RequestBody:获取请求体
	 * 
	 * @ResponseBody:发送json
	 * @RequestBody:获取json
	 * @param employee
	 * @return
	 */
	@RequestMapping("/getjson")
	public String getJosn(@RequestBody Employee employee) {
		System.out.println("请求体:" + employee);
		return "success";
	}

后台接受的数据:


HttpEntity<String> str 比 @RequestBody更强大,还可以获取请求头

ResponseEntity<String>:既可以返回响应数据,还能自定义响应头

java代码:

	@RequestMapping("/test")
	public ResponseEntity<String> haha() {
		String body = "<h1>success</h1>";// 响应体
		MultiValueMap<String, String> headers = new HttpHeaders();
		headers.add("Set-Cookie", "username=admin");
		return new ResponseEntity<String>(body, headers, HttpStatus.OK);
	}

处理结果:

响应头:

响应体:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值