Home > Java > javaTutorial > Introduction to the method of SpringMVC receiving and responding to json data (with code)

Introduction to the method of SpringMVC receiving and responding to json data (with code)

不言
Release: 2019-03-12 15:41:28
forward
4765 people have browsed it

This article brings you an introduction to the method of SpringMVC receiving and responding to json data (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

For front-end and back-end data interaction, in addition to submitting through form forms, you can also transmit and receive json format data to the back-end through ajax (this method can realize the separation of request data and pages). This article will summarize several ways to receive and respond to json data in Spring MVC.

Preparation steps:
1. Import the dependencies of json-related frameworks (such as jackson).
2. The controller method of spring mvc is written normally. If you need to respond to json, add the @responsebody annotation.
3. Before accepting the input parameters corresponding to json, add the @RequestBody annotation.
The server receives json data and restores it to a java object, which is called deserialization. On the contrary, converting the java object into json data as a response and sends it back to the client is called serialization.

Note: Because you want to use ajax, you must introduce jQuery, remember!

jackson maven dependency:

        <!-- jackson依赖 -->
        <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>
Copy after login

1. Receive with entity class

Background: When ajax passes many parameters, it is not convenient 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 on the client and pass it to the background, and the background will use the corresponding entity class to receive it.

Client:

<button onclick="clickMe()">点我</button>
<script>
    function clickMe() {
        $.ajax({
            type : 'POST',
            url : "acceptJsonByEntity",
            contentType : "application/json;charset=utf-8",
            // 如果想以json格式把数据提交到后台的话,JSON.stringify()必须有,否则只会当做表单提交
            data : JSON.stringify({
                "bookId" : 1,
                "author" : "Jack"
            }),
            // 期待返回的数据类型
            dataType : "json",
            success : function(data) {
                var bookId = data.bookId;
                var author = data.author;
                alert("success:" + bookId+','+author);
            },
            error : function(data) {
                alert("error" + data);
            }
        });
</script>
Copy after login
@responseBody annotation is to convert the object returned by the controller method into the specified format through an appropriate converter, and then write it to the body area of ​​the response object, usually with to return JSON data or XML.

@RequestBody annotation is commonly used to handle content whose content-type is not the default application/x-www-form-urlcoded encoding. Generally speaking, it is commonly 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("当前http请求方式为:"+request.getMethod());
        System.out.println("bookId="+book.getBookId()+", author="+book.getAuthor());
        return book;
    }
}
Copy after login

Console output: The current http request method is: POST bookId=1, author=Jack

Client (pop-up window): success :1,Jack


If all methods in the 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 one):

@RestController
public class PassJsonParam {
    @RequestMapping(value="acceptJsonByEntity",method = RequestMethod.POST)
    public Book acceptJsonByEntity(@RequestBody Book book, HttpServletRequest request){
        System.out.println("当前http请求方式为:"+request.getMethod());
        System.out.println("bookId="+book.getBookId()+", author="+book.getAuthor());
        return book;
    }
}
Copy after login

Note: @RestController is used After annotation, the Controller's method can no longer return jsp pages or HTML, and the configured view parser will not work.

2. Receive in map mode

Background: The frontend sends an ajax request to the backend and carries many parameters, but the backend does not have the corresponding entity class to receive it, so how to deal with it? The most common one is the form, where you can consider using map to solve it. Because the data structure of map is in key-value format, we can traverse the search box form, using the name of the form as the key of the map, and the value of the form as the value of the map.

Client:

<form id="bookForm">
    <input type="text" name="bookName" id="bookName">
    <input type="text" name="author" id="author" >
    <button onclick="submitForm(event)">提交</button>
</form>

<script>
    function submitForm(event) {
        //阻止form默认事件
        event.preventDefault();
        //得到搜索框数据
        var map = new Map();
        $("#bookForm input").each(function () {
            var value = $(this).val();      //input 值
            var name = $(this).attr('name');
            map.set(name,value);
        })

        //Map转为Json的方法
        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("失败啦");
            }
        });
    }
</script>
Copy after login

Controller:

    @RequestMapping(value="acceptJsonByMap")
    @ResponseBody
    public Map<String,Object> acceptJsonByMap(@RequestBody Map<String,Object> paramsMap, HttpServletRequest request){
        System.out.println("当前http请求方式为:"+request.getMethod());
        System.out.println(paramsMap);
        return paramsMap;
    }
Copy after login

Console output: The current http request method is: POST {bookName=Love, author=Frank}

Client (Pop-up window): bookName =Love; author=Frank

3. Receive in list mode (passed in json array form)

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("失败啦");
            }
        });
    }
</script>
Copy after login

Note: When passed to the backend, the list should be json format data of [ { key1 : value1} { key2 : value2} ], otherwise a Json parse error may occur.

Controller:

    @RequestMapping(value="acceptJsonByList")
    @ResponseBody
    public List<Book> acceptJsonByList(@RequestBody List<Book> book, HttpServletRequest request){
        System.out.println("当前http请求方式为:"+request.getMethod());
        System.out.println(book);
        return book;
    }
Copy after login

Note: The Book entity class is required here to receive.

Console output: The current http request method is: POST [entity.Book@1138a75c, entity.Book@22d1cbcf]

Client (pop-up window): bookId =123; author=Rose bookId =321; author=Jack

The above is the detailed content of Introduction to the method of SpringMVC receiving and responding to json data (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template