使用Springboot接收前端Ajax发送的json

1. 后端Springboot

通过 https://start.spring.io/ 获得项目框架。在eclipse中导入下载的Maven项目。

  • Maven添加fastjson依赖包

<dependency>
	<groupId>com.alibabagroupId>
	<artifactId>fastjsonartifactId>
	<version>1.2.62version>
dependency>
  • 定义Controller
@RestController
public class GetJsonReq {

	@CrossOrigin
	@RequestMapping(value = "/simple")
	// json的结构和内部字段名称可以与POJO/DTO/javabean完全对应
	public Map<String, String> getJsonBean(@RequestBody Beauty beauty) {
		Map<String, String> result = null;

		if (beauty != null) {
			System.out.println("美女的名字:" + beauty.getName());
			System.out.println("美女的年龄:" + beauty.getAge());

			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			System.out.println("美女出道日期:" + sdf.format(beauty.getDate()));

			System.out.println("美女的收入:" + beauty.getSalary());

			result = new HashMap<>();
			result.put("code", "1");
			result.put("msg", "ok");
		}

		return result;
	}

	@CrossOrigin
	@RequestMapping(value = "/complex")
	//json的结构较为复杂,不直接与POJO/DTO/javabean对应。
	public Map<String, String> getJsonComplex(@RequestBody JSONObject param) {
		Map<String, String> result = null;

		if (param != null) {
			JSONObject master = param.getJSONObject("master");
			Beauty beauty = (Beauty) JSONObject.toJavaObject(master, Beauty.class);
			System.out.println(beauty);

			JSONArray mm = param.getJSONArray("MM");
			for (int i = 0; i < mm.size(); i++) {
				// 这里不能使用get(i),因为get(i)只会得到键值对。
				JSONObject json = mm.getJSONObject(i);
				Beauty bt = (Beauty) JSONObject.toJavaObject(json, Beauty.class);
				System.out.println(bt);
			}

			result = new HashMap<>();
			result.put("code", "1");
			result.put("msg", "ok");
		}

		return result;
	}
}
  • POJO/DTO/JavaBean
    注意Date字段要如何处理。
public class Beauty {
	private String name;
	private int age;
	@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
	private Date date;
	private double salary;

	public Beauty() {

	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public double getSalary() {
		return salary;
	}

	public void setSalary(double salary) {
		this.salary = salary;
	}

	@Override
	public String toString() {
		return "Beauty [name=" + name + ", age=" + age + ", date=" + date + ", salary=" + salary + "]";
	}

}

2. 前端通过Ajax发送json

  • 借助jQuery来发送Ajax请求。

<html>
	<head>
		<meta charset="utf-8">
		<title>发送jsontitle>
		<script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js" type="text/javascript" charset="utf-8">script>
	head>
	<body>
		<script type="text/javascript">
			function send1() {
				var beauty = JSON.stringify({ //将JSON对象转换为字符串
					"name": "小甜甜",
					"age": 26,
					"salary": 200000,
					"date": "2019-08-05 08:04:13"
				});

				$.ajax({
					type: 'POST',
					url: "http://localhost:8080/simple",
					data: beauty,  //beauty是字符串
					contentType: "application/json",
					dataType: "json",
					success: function(message) {
						alert(JSON.stringify(message)) //将JSON对象转换为字符串
					}
				});
			};

			function send2() {
				var beauty = JSON.stringify({
					"MM": [{
						"name": "春花",
						"age": 27,
						"salary": 20000,
						"date": "2017-05-19 09:33:14"
					}, {
						"name": "秋香",
						"age": 30,
						"salary": 30000,
						"date": "2019-10-21 17:04:33"
					}],
					"master": {
						"name": "小甜甜",
						"age": 26,
						"salary": 200000,
						"date": "2019-08-05 08:04:13"
					}
				});

				$.ajax({
					type: "POST",
					url: "http://localhost:8080/complex",
					contentType: "application/json; charset=utf-8",
					data: beauty,
					dataType: "json",
					success: function(message) {
						alert("提交成功" + JSON.stringify(message));
					},
					error: function(message) {
						alert("提交失败" + JSON.stringify(message));
					}
				});
			}
		script>

		<input type="button" name="btn1" id="s1" onclick="send1()" value="发送简单json" />
		<br />
		<hr />
		<input type="button" name="btn2" id="s2" onclick="send2()" value="发送复杂json" />
	body>
html>
  • HTML5中如何实现JSON对象与字符串之间的相互转换?
//string -> json
JSON.parse("...")

//json -> string
JSON.stringify(obj)

3. 使用Java如何模拟客户端发送json的http请求?

  • 看这里

你可能感兴趣的:(前端,java)