Location>code7788 >text

Java back-end request wants to receive multiple objects into the parameter data method

Popularity:108 ℃/2024-11-08 23:35:08

In Java back-end development , if we want to receive multiple objects as HTTP request entry , you can use the Spring Boot framework to simplify this process.Spring Boot provides a powerful RESTful API support , can easily handle a variety of HTTP requests .

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

The following is a detailed example showing how to use Spring Boot to receive an HTTP request containing multiple objects.

1.1 Create a 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 Define the data model

Suppose we have two objects:Usercap (a poem)Address

// 
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 Creating DTO Classes

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 Creating a 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 = ();
 
        // Processing of received data,For example, saving to a database
        ("User ID: " + ());
        ("User Name: " + ());
        ("Address Street: " + ());
        ("Address City: " + ());
        ("Address State: " + ());
 
        return "User and Address received successfully!";
    }
}

1.5 Configuring a Spring Boot Application

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 Preparation of test requests

We can test this API using Postman or curl.

(1) Use of Postman

  1. Open Postman.
  2. Creates a new POST request.
  3. Set the URL tohttp://localhost:8080/api/user-address
  4. Switch toBodytab, selectrawcap (a poem)JSON
  5. Enter the following JSON data:
{
    "user": {
        "id": 1,
        "name": "John Doe"
    },
    "address": {
        "street": "123 Main St",
        "city": "Springfield",
        "state": "IL"
    }
}

6. ClickSendButton.

(2) Using 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 Running the application

Run our Spring Boot application and send a test request. We should see the console output the received user and address information and the API return "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 the data model, DTO class and Controller, we can easily handle complex request data. This example can not only run directly , but also has a certain reference value and practical significance to help us understand how to deal with similar needs in Java back-end development .

2. In the Spring Boot project to create and use the RESTful API

Using RESTful APIs in Spring Boot is very intuitive and efficient, thanks to the strong support provided by the Spring Framework. Here is a step-by-step guide that teaches us how to create and use RESTful APIs in a Spring Boot project.

2.1 Build a 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 an IDE such as IntelliJ IDEA, Eclipse or STS.
  • Manually create a Maven or Gradle project and add the necessary Spring Boot dependencies.

2.2 Adding dependencies

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

<dependencies>.
    <! -- Spring Boot Starter Web: contains everything needed to create a RESTful web service -->
    <dependencies>.
        <groupId> </groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>.

    <! -- Other dependencies such as Spring Data JPA (for database interactions), Spring Boot DevTools (for automatic restarts during development, etc.) -->!
    <! -- ... -->
</dependencies>

2.3 Creating a Controller

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

import .*;
 
@RestController
@RequestMapping("/api/items") // infrastructuralURLtrails
public class ItemController {
 
    // Simulated data sources
    private Map<Long, Item> items = new HashMap<>();
 
    // Create a newItem(POSTrequesting)
    @PostMapping
    public ResponseEntity<Item> createItem(@RequestBody Item item) {
        ((), item);
        return (item);
    }
 
    // Get allItem(GETrequesting)
    @GetMapping
    public ResponseEntity<List<Item>> getAllItems() {
        return (new ArrayList<>(()));
    }
 
    // according toIDGet a singleItem(GETrequesting)
    @GetMapping("/{id}")
    public ResponseEntity<Item> getItemById(@PathVariable Long id) {
        Item item = (id);
        if (item == null) {
            return ().build();
        }
        return (item);
    }
 
    // Update aItem(PUTrequesting)
    @PutMapping("/{id}")
    public ResponseEntity<Item> updateItem(@PathVariable Long id, @RequestBody Item item) {
        Item existingItem = (id);
        if (existingItem == null) {
            return ().build();
        }
        (());
        (());
        return (existingItem);
    }
 
    // Delete aItem(DELETErequesting)
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteItem(@PathVariable Long id) {
        Item item = (id);
        if (item == null) {
            return ().build();
        }
        return ().build();
    }
}

2.4 Creating data models

Data models (also known as entities or DTOs) are classes that represent 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 Launching the application

Ensure that our Spring Boot application has a file containing the@SpringBootApplicationAnnotated main class.

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

2.6 Testing the API

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

(1) Use of Postman

  1. Create a new request.
  2. Select the request type (GET, POST, PUT, DELETE).
  3. Enter the URL (e.g.http://localhost:8080/api/items)。
  4. Add request headers, parameters, or body as needed.
  5. Send a request and see the response.

(2) Using curl

# Create a newItem
curl -X POST http://localhost:8080/api/items -H "Content-Type: application/json" -d '{
    "id": 1,
    "name": "Item Name",
    "description": "Item Description"
}'
 
# Get allItem
curl http://localhost:8080/api/items
 
# according toIDGet a singleItem
curl http://localhost:8080/api/items/1
 
# Update aItem
curl -X PUT http://localhost:8080/api/items/1 -H "Content-Type: application/json" -d '{
    "name": "Updated Item Name",
    "description": "Updated Item Description"
}'
 
# Delete aItem
curl -X DELETE http://localhost:8080/api/items/1

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