SoFunction
Updated on 2025-03-03

Java backend requests to receive multiple objects into parameters (recommended)

In Java backend development, if we want to receive multiple objects as incoming parameters for HTTP requests, we can use the Spring Boot framework to simplify this process. Spring Boot provides powerful RESTful API support, which can easily handle various HTTP requests.

1. Example: Use Spring Boot to receive HTTP requests containing multiple objects

Here is a detailed example showing how to use Spring Boot to receive HTTP requests containing multiple objects.

1.1 Create Spring Boot Project

First, make sure we have Spring Boot and Maven (or Gradle) installed. We can use Spring Initializr to quickly generate a Spring Boot project.

1.2 Defining a data model

Suppose we have two objects:UserandAddress

// 
public class User {
    private Long id;
    private String name;
    // Getters and Setters
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
         = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
         = name;
    }
}
// 
public class Address {
    private String street;
    private String city;
    private String state;
    // Getters and Setters
    public String getStreet() {
        return street;
    }
    public void setStreet(String street) {
         = street;
    }
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
         = city;
    }
    public String getState() {
        return state;
    }
    public void setState(String state) {
         = state;
    }
}

1.3 Create a DTO class

Create a DTO class to encapsulate multiple objects.

// 
public class UserAddressDTO {
    private User user;
    private Address address;
    // Getters and Setters
    public User getUser() {
        return user;
    }
    public void setUser(User user) {
         = user;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
         = address;
    }
}

1.4 Create Controller

Write an endpoint in the Controller to receive requests containing multiple objects.

// 
import .*;
@RestController
@RequestMapping("/api")
public class UserAddressController {
    @PostMapping("/user-address")
    public String receiveUserAddress(@RequestBody UserAddressDTO userAddressDTO) {
        User user = ();
        Address address = ();
        // Process the received data, for example, save it to the database        ("User ID: " + ());
        ("User Name: " + ());
        ("Address Street: " + ());
        ("Address City: " + ());
        ("Address State: " + ());
        return "User and Address received successfully!";
    }
}

1.5 Configuring Spring Boot Applications

Make sure our Spring Boot application has a main class to start the application.

// 
import ;
import ;
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        (, args);
    }
}

1.6 Writing a test request

We can use Postman or curl to test this API.

(1) Use Postman

  • Open Postman.
  • Create a new POST request.
  • Set the URL tohttp://localhost:8080/api/user-address
  • Switch toBodyTab, selectrawandJSON
  • Enter the following JSON data:
{
    "user": {
        "id": 1,
        "name": "John Doe"
    },
    "address": {
        "street": "123 Main St",
        "city": "Springfield",
        "state": "IL"
    }
}

6. ClickSendbutton.

(2) Use curl

curl -X POST http://localhost:8080/api/user-address -H "Content-Type: application/json" -d '{
    "user": {
        "id": 1,
        "name": "John Doe"
    },
    "address": {
        "street": "123 Main St",
        "city": "Springfield",
        "state": "IL"
    }
}'

1.7 Run the application

Run our Spring Boot app and send a test request. We should see the console output the received user and address information, and the API returns "User and Address received successfully!".

1.8 Summary

The above example shows how to use Spring Boot to receive HTTP requests containing multiple objects. By defining data models, DTO classes, and Controllers, we can easily handle complex request data. This example can not only run directly, but also has certain reference value and practical significance, which can help us understand how to deal with similar requirements in Java backend development.

2. Create and use RESTful API in Spring Boot project

In Spring Boot, using the RESTful API is very intuitive and efficient, thanks to the powerful support provided by the Spring framework. Here is a step-by-step guide to how to create and use RESTful APIs in Spring Boot projects.

2.1 Build Spring Boot Project

First, we need a Spring Boot project. We can create it in one of the following ways:

  • Use the Spring Initializr website to generate the project and download it as a Maven or Gradle project.
  • Use the built-in Spring Initializr tool in IDEs such as IntelliJ IDEA, Eclipse, or STS.
  • Create a Maven or Gradle project manually and add the necessary Spring Boot dependencies.

2.2 Add dependencies

For RESTful APIs, we usually need the following dependencies (if we are using Maven):

<dependencies>
    <!-- Spring Boot Starter Web: Include creationRESTful WebAll the content required for the service -->
    <dependency>
        <groupId></groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Other dependencies,likeSpring Data JPA(For database interaction)、Spring Boot DevTools(Used for automatic restart during development, etc.) -->
    <!-- ... -->
</dependencies>

2.3 Create Controller

Controller is the core component that handles HTTP requests. We can use@RestControllerAnnotation to create a RESTful Controller.

import .*;
@RestController
@RequestMapping("/api/items") // Basic URL pathpublic class ItemController {
    // Simulated data source    private Map<Long, Item> items = new HashMap<>();
    // Create a new Item (POST request)    @PostMapping
    public ResponseEntity<Item> createItem(@RequestBody Item item) {
        ((), item);
        return (item);
    }
    // Get all Items (GET request)    @GetMapping
    public ResponseEntity<List<Item>> getAllItems() {
        return (new ArrayList<>(()));
    }
    // Get a single Item based on ID (GET request)    @GetMapping("/{id}")
    public ResponseEntity<Item> getItemById(@PathVariable Long id) {
        Item item = (id);
        if (item == null) {
            return ().build();
        }
        return (item);
    }
    // Update an Item (PUT request)    @PutMapping("/{id}")
    public ResponseEntity<Item> updateItem(@PathVariable Long id, @RequestBody Item item) {
        Item existingItem = (id);
        if (existingItem == null) {
            return ().build();
        }
        (());
        (());
        return (existingItem);
    }
    // Delete an Item (DELETE request)    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteItem(@PathVariable Long id) {
        Item item = (id);
        if (item == null) {
            return ().build();
        }
        return ().build();
    }
}

2.4 Creating a Data Model

A data model (also known as an entity or DTO) is a class that represents business data.

public class Item {
    private Long id;
    private String name;
    private String description;
    // Getters and Setters
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
         = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
         = name;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
         = description;
    }
}

2.5 Start the application

Make sure our Spring Boot app has a included@SpringBootApplicationThe main class of the annotation.

import ;
import ;
@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        (, args);
    }
}

2.6 Test API

We can use Postman, curl, or other HTTP clients to test our RESTful API.

(1) Use Postman

  • Create a new request.
  • Select the request type (GET, POST, PUT, DELETE).
  • Enter the URL (for example,http://localhost:8080/api/items)。
  • Add request headers, parameters, or body as needed.
  • Send a request and view the response.

(2) Use curl

# Create a new Itemcurl -X POST http://localhost:8080/api/items -H "Content-Type: application/json" -d '{
    "id": 1,
    "name": "Item Name",
    "description": "Item Description"
}'
# Get all Itemscurl http://localhost:8080/api/items
# Get a single Item by IDcurl http://localhost:8080/api/items/1
# Update an Itemcurl -X PUT http://localhost:8080/api/items/1 -H "Content-Type: application/json" -d '{
    "name": "Updated Item Name",
    "description": "Updated Item Description"
}'
# Delete an Itemcurl -X DELETE http://localhost:8080/api/items/1

Through the above steps, we can create and use the RESTful API in Spring Boot. These APIs can be used to interact with front-end applications, mobile applications, or other microservices.

This is the article about the data method of Java backend requesting to receive multiple objects into parameters. For more related Java backend requesting to receive multiple objects into parameters, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!