示例【Spring Boot处理JSON数据】
程序清单:/springboot2/src/main/java/com/dwx/hello/User.java
package com.dwx.hello;
public class User {
private String userName;
private String sex;
private Integer age;
public User() {}
public User(String userName,String sex,Integer age) {
this.userName=userName;
this.sex=sex;
this.age=age;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "User [userName=" + userName + ", sex=" + sex + ", age=" + age + "]";
}
}
程序清单:/springboot2/src/main/resources/templates/index.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Boot处理JSON数据</title>
<link rel="stylesheet" th:href="@{css/bootstrap.min.css}">
<link rel="stylesheet" th:href="@{css/bootstrap-theme.min.css}"/>
<script type="text/javascript" th:src="@{js/jquery-1.11.0.min.js}"></script>
<script type="text/javascript" th:src="@{js/bootstrap.min.js}"></script>
<script type="text/javascript">
$(document).ready(function(){
findBook();
});
function findBook(){
$.ajax("/findUser",// 发送请求的URL字符串。
{
dataType : "json", // 预期服务器返回的数据类型。
type : "post", // 请求方式 POST或GET
contentType:"application/json", // 发送信息至服务器时的内容编码类型
// 发送到服务器的数据。
data:JSON.stringify({userName : "jack"}),
async: true , // 默认设置下,所有请求均为异步请求。如果设置为false,则发送同步请求
// 请求成功后的回调函数。
success :function(data){
console.log(data);
$("#userName").html(data.userName);
$("#sex").html(data.sex);
$("#age").html(data.age);
},
// 请求出错时调用的函数
error:function(){
alert("数据发送失败");
}
});
}
</script>
</head>
<body>
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Spring Boot处理JSON数据</h3>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-4">
<p>用户名:<span id="userName"></span></p>
<p>性别:<span id="sex"></span></p>
<p>年龄:<span id="age"></span></p>
</div>
</div>
</div>
</body>
</html>
程序清单:/springboot2/src/main/java/com/dwx/hello/UserController.java
package com.dwx.hello;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@RequestMapping("/findUser")
public User findUser(@RequestBody User user) {
System.out.println(user);
user.setSex("男");
user.setAge(22);
return user;
}
}
启动Spring Boot项目,访问如下地址:http://localhost:8080/
控制台输出
页面输出