添加json依赖
<!--spring-json依赖--><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.0</version></dependency>
注解
-
@RequestBody:作用是接收前端ajax传递给后端的json字符串,并将json格式的数据转为java对象
-
@ResponseBody:作用是将java对象转为json格式的数据传递给前台ajax
案例
-
编写controller
@Controller
@RequestMapping("/account")
public class AccountController {@PostMapping("/findAccount12")@ResponseBodypublic JsonStatus findAccount12(@RequestBody Account account) {//Map<String ,Object> map = new HashMap<>();//map.put("status",200);//map.put("msg",account);JsonStatus jsonStatus = new JsonStatus();try {//System.out.println(1/0);jsonStatus.setStatus(200);jsonStatus.setMsg(account);} catch (Exception e) {e.printStackTrace();jsonStatus.setStatus(500);jsonStatus.setMsg("查询错误!!!");}return jsonStatus;}
}
添加实体类:
/** Copyright (c) 2020, 2024, All rights reserved.**/
package com.by.pojo;/*** <p>Project: SpringMVC - JsonStatus</p>* <p>Powered by scl On 2024-01-09 17:03:33</p>* <p>描述:<p>** @author 孙臣龙 [1846080280@qq.com]* @version 1.0* @since 17*/
public class JsonStatus {private Integer status;private Object msg;public Integer getStatus() {return status;}public void setStatus(Integer status) {this.status = status;}public Object getMsg() {return msg;}public void setMsg(Object msg) {this.msg = msg;}
}
在index.jsp里面定义ajax请求
-
添加按钮
<input type="button" value="测试ajax请求json和响应json" id="testJson"/>
引入js库文件
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
编写ajax代码
<script type="text/javascript">$(function(){$("#testJson").click(function(){$.ajax({type:"post",url:"/account/saveAccount2",contentType:"application/json;charset=UTF-8",data:'{"id":1,"name":"张二狗","money":999.0}',success:function(data){if(data.status == 200){alert(data.msg.name);alert(data.msg.money);}}})});})</script>
结果展示: