思路
目标
引入依赖
接收ajax复杂对象
实现
引入依赖
<!-- Spring进行JSON数据转换依赖 -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
接收Ajax复杂对象
创建对象
package com.atguigu.crowd.entity;
import java.util.List;
import java.util.Map;
public class Student {
private Integer stuId;
private String stuName;
private Address address;
private List<Subject> subjectList;
private Map<String, String> map;
public Student() {
}
public Student(Integer stuId, String stuName, Address address, List<Subject> subjectList, Map<String, String> map) {
super();
this.stuId = stuId;
this.stuName = stuName;
this.address = address;
this.subjectList = subjectList;
this.map = map;
}
@Override
public String toString() {
return "Student [stuId=" + stuId + ", stuName=" + stuName + ", address=" + address + ", subjectList="
+ subjectList + ", map=" + map + "]";
}
public Integer getStuId() {
return stuId;
}
public void setStuId(Integer stuId) {
this.stuId = stuId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public List<Subject> getSubjectList() {
return subjectList;
}
public void setSubjectList(List<Subject> subjectList) {
this.subjectList = subjectList;
}
public Map<String, String> getMap() {
return map;
}
public void setMap(Map<String, String> map) {
this.map = map;
}
}
package com.atguigu.crowd.entity;
public class Address {
private String province;
private String city;
private String street;
public Address() {
}
public Address(String province, String city, String street) {
super();
this.province = province;
this.city = city;
this.street = street;
}
@Override
public String toString() {
return "Address [province=" + province + ", city=" + city + ", street=" + street + "]";
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}
package com.atguigu.crowd.entity;
public class Subject {
private String subjectName;
private Integer subjectScore;
public Subject() {
}
public Subject(String subjectName, Integer subjectScore) {
super();
this.subjectName = subjectName;
this.subjectScore = subjectScore;
}
@Override
public String toString() {
return "Subject [subjectName=" + subjectName + ", subjectScore=" + subjectScore + "]";
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
public Integer getSubjectScore() {
return subjectScore;
}
public void setSubjectScore(Integer subjectScore) {
this.subjectScore = subjectScore;
}
}
handler
@ResponseBody
@RequestMapping("/send/compose/object.html")
public String testReceiveComposeObject(@RequestBody Student student) {
System.out.println(student.toString());
return "success";
}
jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<base herf="http://${pageContext.request.serverName}:${pageContext.request.serverPort }${pageContext.request.contextPath } }/"/>
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
</head>
<body>
<!-- <a href="test/ssm.html">test</a> -->
<button id="btn1">Test1 Request Body</button>
<button id="btn2">Test2 Request Body</button>
<button id="btn3">Test3 Request Body</button>
<button id="btn4">Test4 Request Body</button>
</body>
<script>
$(function(){
$("#btn1").click(function(){
$.ajax({
"url":"send/array.html",
"type": "post",
"data":{
"array":[5,8,12]
},
"dataType": "text",
"success": function(response){
alert(response);
},
"error": function(response){
alert(response);
},
});
});
$("#btn2").click(function(){
$.ajax({
"url":"send/array/two.html",
"type": "post",
"data":{
"array[0]":5,
"array[1]":8,
"array[2]":12,
},
"dataType": "text",
"success": function(response){
alert(response);
},
"error": function(response){
alert(response);
},
});
});
$("#btn3").click(function(){
var array = [5,8,12];
var requestBody = JSON.stringify(array);
$.ajax({
"url":"send/array/three.html",
"type": "post",
"data": requestBody,
"contentType":"application/json;charaset=UTF-8",
"dataType": "text",
"success": function(response){
alert(response);
},
"error": function(response){
alert(response);
},
});
});
$("#btn4").click(function(){
var student = {
"stuId":5,
"stuName":"tom",
"address":{
"province":"广东",
"city":"深圳",
"street":"后瑞"
},
"subjectList": [
{
"subjectName":"JavaSE",
"subjectScore":100
},{
"subjectName":"SSM",
"subjectScore":99
}
],
"map":{
"k1":"v1",
"k2":"v2"
}
};
var requestBody = JSON.stringify(student);
$.ajax({
"url":"send/compose/object.html",
"type": "post",
"data": requestBody ,
"contentType":"application/json;charaset=UTF-8",
"dataType": "text",
"success": function(response){
alert(response);
},
"error": function(response){
alert(response);
},
});
});
});
</script>
</html>
可以引入错误消息提示机制
java
package com.atguigu.crowd.entity;
public class ResultEntity<T> {
public static final String SUCCESS = "SUCCESS";
public static final String FAILED = "FAILED";
// 是否成功
private String result;
// 错误消息
private String message;
// 数据
private T data;
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public static <Type> ResultEntity<Type> successWithoutData() {
return new ResultEntity<Type> (SUCCESS,null,null);
}
public static <Type> ResultEntity<Type> successWithData(Type Data) {
return new ResultEntity<Type> (SUCCESS,null,Data);
}
public static <Type> ResultEntity<Type> failed(String message) {
return new ResultEntity<Type> (FAILED,message,null);
}
public ResultEntity() {
// TODO Auto-generated constructor stub
}
public ResultEntity(String result, String message, T data) {
super();
this.result = result;
this.message = message;
this.data = data;
}
@Override
public String toString() {
return "ResultEntity [result=" + result + ", message=" + message + ", data=" + data + "]";
}
}
jsp
<script>
$("#btn5").click(function(){
var student = {
"stuId":5,
"stuName":"tom",
"address":{
"province":"广东",
"city":"深圳",
"street":"后瑞"
},
"subjectList": [
{
"subjectName":"JavaSE",
"subjectScore":100
},{
"subjectName":"SSM",
"subjectScore":99
}
],
"map":{
"k1":"v1",
"k2":"v2"
}
};
var requestBody = JSON.stringify(student);
$.ajax({
"url":"send/compose/object01.json",
"type": "post",
"data": requestBody ,
"contentType":"application/json;charaset=UTF-8",
"dataType": "json",
"success": function(response){
console.log(response);
},
"error": function(response){
console.log(response);
},
});
});
</script>
注意
如何判断是不是Ajax请求?
依赖
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.atguigu.crowd</groupId>
<artifactId>atcrowdfunding05-common-util</artifactId>
<version>0.0.1-SNAPSHOT</version>
<!-- 引入Servlet容器中相关依赖 -->
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
java util
package com.atguigu.crowd.util;
import javax.servlet.http.HttpServletRequest;
public class CrowdUtil {
public static boolean judgeRequestType(HttpServletRequest request) {
String acceptHeader = request.getHeader("Accept");
String xRequestHeader = request.getHeader("X-Requested-With");
return (acceptHeader!=null&&acceptHeader.contains("application/json"))
||
(xRequestHeader != null&&xRequestHeader.equals("XMLHttpRequest"));
}
}
控制器
package com.atguigu.crowd.mvc.handler;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.atguigu.crowd.entity.Admin;
import com.atguigu.crowd.entity.ParamData;
import com.atguigu.crowd.entity.ResultEntity;
import com.atguigu.crowd.entity.Student;
import com.atguigu.crowd.service.api.AdminService;
import com.atguigu.crowd.util.CrowdUtil;
@Controller
public class TestHandler {
@Autowired
private AdminService adminService;
@ResponseBody
@RequestMapping("/send/array.html")
public String testReceiveArrayOne(@RequestParam("array[]") List<Integer> array) {
for(Integer number : array) {
System.out.println("number="+number);
}
return "success";
}
@ResponseBody
@RequestMapping("/send/array/two.html")
public String testReceiveArrayTwo(ParamData paramData) {
List<Integer> array = paramData.getArray();
for(Integer number : array) {
System.out.println("number="+number);
}
return "success";
}
@ResponseBody
@RequestMapping("/send/array/three.html")
public String testReceiveArrayThree(@RequestBody List<Integer> array) {
for(Integer number : array) {
System.out.println("number="+number);
}
return "success";
}
@ResponseBody
@RequestMapping("/send/compose/object.html")
public String testReceiveComposeObject(@RequestBody Student student) {
System.out.println(student.toString());
return "success";
}
@ResponseBody
@RequestMapping("/send/compose/object01.json")
public ResultEntity<Student> testReceiveComposeObject01(@RequestBody Student student,HttpServletRequest request) {
boolean judgeResult = CrowdUtil.judgeRequestType(request);
System.out.println("judgeResult="+judgeResult);
System.out.println(student.toString());
ResultEntity<Student> resultEntity = ResultEntity.successWithData(student);
return resultEntity;
}
@RequestMapping("/test/ssm.html")
public String testSsm(ModelMap modelMap,HttpServletRequest request) {
boolean judgeResult = CrowdUtil.judgeRequestType(request);
System.out.println("judgeResult="+judgeResult);
List<Admin> adminList = adminService.getAll();
modelMap.addAttribute("adminList",adminList);
// System.out.println(10/0);
return "target";
}
}