目标
- 通过ajax向服务器传递json格式的数据
- 服务器接收json格式的数据后, 返回json格式的数据
单个对象的json格式数据, json数组对象
视图
纯html页面文件view/index.html(根据配置文件中静态资源映射设置, 实际目录是p/index.html)内容如下:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
<script type="text/javascript" src="jquery-3.3.1.min.js"></script>
<script type="text/javascript">
function send1_OnClicked() {
var account = {};
account['accountID'] = "62001";
account['balance'] = 100;
$.ajax({
type: "POST",
url: "../rest/getjson1",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(account),
success: function (data) {
var account = data;
$("#account").html(account.accountID + ":" + account.balance);
},
error: function (data) {
console.log("error...");
console.log(data);
}
});
}
function send2_OnClicked() {
var account = {};
account['accountID'] = "62002";
account['balance'] = 200;
console.log(JSON.stringify(account));
$.ajax({
type: "POST",
url: "../rest/getjson2",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(account),
success: function (data) {
var account = data;
$("#account").html(account.accountID + ":" + account.balance);
},
error: function (data) {
console.log("error...");
console.log(data);
}
});
}
function send3_OnClicked() {
var accounts = [];
var account1 = {"accountID": "62001", "balance": "100"};
var account2 = {"accountID": "62002", "balance": "200"};
var account3 = {"accountID": "62003", "balance": "300"};
accounts.push(account1);
accounts.push(account2);
accounts.push(account3);
console.log(JSON.stringify(accounts));
$.ajax({
type: "POST",
url: "../rest/getjson3",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(accounts),
success: function (data) {
var account = data;
$("#account").html(account.accountID + ":" + account.balance);
},
error: function (data) {
console.log("error...");
console.log(data);
}
});
}
function send4_OnClicked() {
var accounts = [];
var account1 = {"accountID": "62001", "balance": "100"};
var account2 = {"accountID": "62002", "balance": "200"};
var account3 = {"accountID": "62003", "balance": "300"};
var account4 = {"accountID": "62004", "balance": "400"};
accounts.push(account1);
accounts.push(account2);
accounts.push(account3);
accounts.push(account4);
$.ajax({
type: "POST",
url: "../rest/getjson4",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(accounts),
success: function (data) {
$("#account").html(data.accounts.length + ":" + data.accounts[0].accountID + ":" + data.accounts[0].balance);
},
error: function (data) {
console.log("error...");
console.log(data);
}
});
}
</script>
</head>
<body>
<h1 id ="account">Hello World!</h1>
<input type="button" value="send1" onclick="send1_OnClicked()" />
<input type="button" value="send2" onclick="send2_OnClicked()" />
<input type="button" value="send3" onclick="send3_OnClicked()" />
<input type="button" value="send4" onclick="send4_OnClicked()" />
</body>
</html>
控制器
需要下载三个jackson的jar文件, 加入到项目中, 用于处理json数据. 下载链接https://pan.baidu.com/s/1wqEz-QSfvwL_WB18z0B_uA
文件controller/DemoRestController.java内容如下:
package controller;
import java.util.List;
import model.Account;
import model.AccountList;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/rest")
public class DemoRestController {
@RequestMapping(value = "/getjson1", produces = {"application/json;charset=UTF-8"})
public Account getjson1(@RequestBody Account account) {
System.out.println(account.getAccountID() + ":" + account.getBalance());
return new Account(account.getAccountID() + "getjson1测试", account.getBalance() + 200);
}
@RequestMapping(value = "/getjson2", produces = {"application/json;charset=UTF-8"})
public Account getjson2(HttpEntity<Account> httpEntity) {
Account account = httpEntity.getBody();
System.out.println(account.getAccountID() + ":" + account.getBalance());
return new Account(account.getAccountID() + "getjson12测试", account.getBalance() + 200);
}
@RequestMapping(value = "/getjson3", produces = {"application/json;charset=UTF-8"})
public Account getjson3(@RequestBody List<Account> accounts) {
accounts.stream().forEach((account) -> {
System.out.println(account.getAccountID() + ":" + account.getBalance());
});
return new Account(accounts.get(0).getAccountID() + "getjson3", accounts.get(0).getBalance() + 200);
}
@RequestMapping(value = "/getjson4", produces = {"application/json;charset=UTF-8"})
public AccountList getjson4() {
AccountList accounts = new AccountList();
for (int i = 0; i < 10; i++) {
accounts.getAccounts().add(new Account("getjson4" + i + Math.random(), (int) (Math.random() * 1000)));
}
return accounts;
}
}
模型
文件model/Account.java内容如下:
package model;
public class Account {
private String accountID;
private int balance;
public Account() {
}
public Account(String accountID) {
this.accountID = accountID;
}
public Account(String accountID, int balance) {
this.accountID = accountID;
this.balance = balance;
}
public int getBalance() {
return balance;
}
public void setBalance(int balance) {
this.balance = balance;
}
public String getAccountID() {
return accountID;
}
public void setAccountID(String accountID) {
this.accountID = accountID;
}
}
文件model/AccountList.java内容如下:
package model;
import java.util.ArrayList;
import java.util.List;
public class AccountList {
private List<Account> accounts;
public AccountList() {
this.accounts = new ArrayList<>();
}
public AccountList(List<Account> accounts) {
this.accounts = accounts;
}
public List<Account> getAccounts() {
return accounts;
}
public void setAccounts(List<Account> accounts) {
this.accounts = accounts;
}
}
配置文件
配置文件config/SpringMvcInitializer,java内容如下:
package config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class SpringMvcInitializer implements WebApplicationInitializer { //实现这个接口是关键, 与类名无关.
@Override
public void onStartup(ServletContext sc) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(AppConfig.class); //自己定义的AppConfig类.
context.setServletContext(sc);
ServletRegistration.Dynamic servlet = sc.addServlet("dispatcher", new DispatcherServlet(context));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
配置文件config/AppConfig.java内容如下:
package config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"controller"})
public class AppConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/view/**").addResourceLocations("/p/"); //静态资源映射
registry.addResourceHandler("/index.html").addResourceLocations("/index.html"); //静态资源映射
}
}
项目结构
由于需要进行json格式的数据解析和合成, 需要依赖的java的json工具包jackson.
项目的具体结构如下:
运行结果
初始页面
点击按钮1, 得到
点击按钮2, 得到
点击按钮3, 得到
点击按钮4, 得到类似下面的结果, 其中有随机数
调试
使用Chrome观察执行过程和调试