Several Ways of SpringMVC Receiving and Responding to json Data
- 2021-07-03 00:11:12
- OfStack
Preface
In addition to submitting data through form form, data in json format can also be transmitted and received to the back end through ajax (this way can realize the separation of request data and page). This article will summarize several ways to receive and respond to json data in Spring MVC under 1.
I don't have much to say. Let's take a look at the detailed introduction
Preparation steps:
1. Import json related framework dependencies (such as jackson).
2. The controller method of spring mvc writes normally. If you need to respond to json, add @ responsebody annotation.
3. Add the @ RequestBody annotation before accepting the input parameters corresponding to json.
The server receives json data and restores it to java object, which is called deserialization. On the contrary, it converts java object as response to json data and sends it back to the client, which is called serialization.
Note: Because you want to use ajax, all 1s must introduce jQuery, remember!
jackson maven Dependence:
<!-- jackson Dependency -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.7.0</version>
</dependency>
1. Receive as Entity Class
BACKGROUND: When ajax passes more parameters, it is inconvenient to use parameter name matching method. If there is a corresponding entity class in the background, you can choose to encapsulate the data in json format at the client and pass it to the background, and the background will receive it with the corresponding entity class.
Client:
<button onclick="clickMe()"> Order me </button>
<script>
function clickMe() {
$.ajax({
type : 'POST',
url : "acceptJsonByEntity",
contentType : "application/json;charset=utf-8",
// If you want to use json Format to submit the data to the background, JSON.stringify() Must have, otherwise it will only be submitted as a form
data : JSON.stringify({
"bookId" : 1,
"author" : "Jack"
}),
// The type of data expected to be returned
dataType : "json",
success : function(data) {
var bookId = data.bookId;
var author = data.author;
alert("success:" + bookId+','+author);
},
error : function(data) {
alert("error" + data);
}
});
</script>
The @ responseBody annotation is written to the body section of the response object after the object returned by the controller method is converted to the specified format by an appropriate converter, which is usually used to return JSON data or XML.
The @ RequestBody annotation is often used to deal with content where content-type is not the default application/x-www-form-urlcoded encoding. 1 Generally speaking, it is often used to deal with application/json types.
Controller:
@Controller
public class PassJsonParam {
@RequestMapping(value="acceptJsonByEntity",method = RequestMethod.POST)
@ResponseBody
public Book acceptJsonByEntity(@RequestBody Book book, HttpServletRequest request){
System.out.println(" Current http Request mode is :"+request.getMethod());
System.out.println("bookId="+book.getBookId()+", author="+book.getAuthor());
return book;
}
}
Console output: The current http request mode is: POST bookId=1, author=Jack
Client (pop-up window): success: 1, Jack
If all methods in Controller need to return json format data, you can use the @ RestController annotation.
@RestController = @Controller + @ResponseBody
Controller (the above Controller can be replaced with the following):
@RestController
public class PassJsonParam {
@RequestMapping(value="acceptJsonByEntity",method = RequestMethod.POST)
public Book acceptJsonByEntity(@RequestBody Book book, HttpServletRequest request){
System.out.println(" Current http Request mode is :"+request.getMethod());
System.out.println("bookId="+book.getBookId()+", author="+book.getAuthor());
return book;
}
}
Note: With the @ RestController annotation, the Controller method can no longer return to the jsp page or html, and the configured view parser will not work.
2. Receive in map
Background: The foreground sends ajax requests to the background and carries many parameters, but the background does not have a corresponding entity class to receive. What should I do? The most common one is the form, which can be solved by map. Because the data structure of map is in the form of key-value, we can traverse the search box form, taking name of the form as key of map and value of the form as map.
Client:
<form id="bookForm">
<input type="text" name="bookName" id="bookName">
<input type="text" name="author" id="author" >
<button onclick="submitForm(event)"> Submit </button>
</form>
<script>
function submitForm(event) {
// Block form Default event
event.preventDefault();
// Get the search box data
var map = new Map();
$("#bookForm input").each(function () {
var value = $(this).val(); //input Value
var name = $(this).attr('name');
map.set(name,value);
})
//Map Convert to Json Method of
var obj= Object.create(null);
for (var [k,v] of map) {
obj[k] = v;
}
$.ajax({
type: 'POST',
contentType:'application/json',
url: "acceptJsonByMap",
data: JSON.stringify(obj),
dataType: 'json',
success: function (data) {
var bookName = data.bookName;
var author = data.author;
alert("bookName ="+bookName+"; author="+author);
},
error: function (data) {
alert(" Failure ");
}
});
}
</script>
Controller:
@RequestMapping(value="acceptJsonByMap")
@ResponseBody
public Map<String,Object> acceptJsonByMap(@RequestBody Map<String,Object> paramsMap, HttpServletRequest request){
System.out.println(" Current http Request mode is :"+request.getMethod());
System.out.println(paramsMap);
return paramsMap;
}
Console output: The current http request mode is: POST {bookName=Love, author=Frank}
Client (pop-up window): bookName = Love; author=Frank
3. Receive as list (passed as an json array)
Client:
<button onclick="clickHere()">clickHere</button>
<script>
function clickHere() {
var params1 = {
"bookId":"123",
"author":"Rose"
};
var params2 = {
"bookId":"321",
"author":"Jack"
};
var list = [];
list.push(params1);
list.push(params2);
$.ajax({
type: 'POST',
contentType:'application/json',
url: "acceptJsonByList",
data: JSON.stringify(list),
dataType: 'json',
success: function (data) {
for (let i = 0; i < data.length; i++) {
var bookId = data[i].bookId;
var author = data[i].author;
alert("bookId ="+bookId+"; author="+author);
}
},
error: function (data) {
alert(" Failure ");
}
});
}
</script>
Note: When passed to the back end, list should be json format data of [{key1: value1} {key2: value2}], otherwise an Json parse error error may occur.
Controller:
@RequestMapping(value="acceptJsonByList")
@ResponseBody
public List<Book> acceptJsonByList(@RequestBody List<Book> book, HttpServletRequest request){
System.out.println(" Current http Request mode is :"+request.getMethod());
System.out.println(book);
return book;
}
Note: This requires the Book entity class to receive.
Console output: The current http request mode is: POST [entity. Book @ 1138a75c, entity. Book @ 22d1cbcf]
Client (pop-up window): bookId = 123; author = Rose bookId = 321; author=Jack
Summarize