Spring MVC uses Ajax to pass an object to the controller

preface

Recently, I was writing a project based on spring MVC + Spring + mybatis, which involves the function of sending data to the controller with Ajax. Because I don't want to use spring's form tag, I want to see if there is a way to directly convert JSON data in Ajax into objects in the controller method to receive and process. The following will gradually introduce the methods of transferring JSON data and encapsulating it in different situations. Let's take a look at the detailed introduction:

Foundation type

If the passed JSON data is the basic type (int, string, etc.), you only need to mark the parameters in the method with @ requestparam.

Ajax code

java code

Here @ ResponseBody indicates that an object is returned@ There are many uses of requestparam. For details, please refer to the spring MVC documentation

Simple object type

Simple object type means that the object does not contain complex data structures, such as list, map, etc. Here, you can use the tag @ modelattribute to directly encapsulate JSON data into objects.

Suppose we have a user object whose attributes include name and age

The data transmitted by AJAX is as follows

The code in the controller is as follows

Spring MVC temporarily does not support receiving and generating multiple modelatttributes

Array type

In some cases, you may need to pass a set of data of the same type, such as adding a set of user information. This is an array that can be passed to the controller method through Ajax. Refer to this answer for details

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>