Sitemap

Mastering Spring Boot Request Handling: Annotations and Practical Examples

4 min readAug 21, 2023
Press enter or click to view image in full size

Hello there! In today’s journey through the world of Spring Boot, we’re going to explore the art of handling different types of HTTP requests. Spring Boot is renowned for its simplicity and efficiency, and it comes with a powerful arsenal of annotations for request handling. So, let’s dive into it.

Navigating Through Annotations

1) Handling GET Requests with Query Parameters

Curl:

curl -X GET "http://localhost:8080/api/resource?param1=value1&param2=value2"

In Spring how this request translates to is presented below:

@RequestParam is used in Spring boot for this type of handling

  • It is a Spring Framework annotation used in Java to extract values from HTTP request parameters, making it easy to access data sent in query strings or as form parameters in web applications.

Java:

@GetMapping("/resource")
public ResponseEntity<String> getResource(
@RequestParam("param1") String param1,
@RequestParam("param2") String param2) {
// Handle the GET request with query parameters here
return ResponseEntity.ok("Received param1: " + param1 + " and param2: " + param2);
}

2) Handling POST Requests with JSON Request Body

Now, if you’re on a mission to send data to the server via POST requests, Spring Boot offers several paths to choose from.

a. Request Body with a Map or List

Curl:

curl -X POST "http://localhost:8080/api/resource"
-H "Content-Type: application/json"
-d '{"key1":"value1","key2":"value2"}'

In Spring how this request translates to is presented below:

@RequestBodyis used in Spring boot for this type of handling

It is a Spring Framework annotation used in Java to indicate that the method parameter should be bound to the body of the HTTP request, allowing you to receive and process incoming JSON or XML data seamlessly within your Spring controller method. It simplifies the parsing of request data into Java objects.

Java:

@PostMapping("/resource")
public ResponseEntity<String> createResource(@RequestBody Map<String, String> requestBody) {
// Handle the POST request with a JSON request body as a Map
return ResponseEntity.ok("Received JSON body: " + requestBody.toString());
}

b. Request Body with a DTO (Data Transfer Object)

Curl:

curl -X POST "http://localhost:8080/api/resource"
-H "Content-Type: application/json"
-d '{
"property1": "value1",
"property2": "value2"
}'

Java:

@PostMapping("/resource")
public ResponseEntity<String> createResource(@RequestBody ItemDTO itemDTO) {
// Handle the POST request with a JSON request body as a DTO
return ResponseEntity.ok("Received DTO: " + itemDTO.toString());
}

3) Handling POST Requests with File Upload

In your adventures, you’ll often encounter tasks like file uploads. Fear not; Spring Boot simplifies the process.

a. Single File Upload

Curl:

curl -X POST "http://localhost:8080/api/upload"
-F "file=@/path/to/your/file.jpg"

In Spring how this request translates to is presented below:

Again here we can use @RequestParam along with MultipartFile

It is a Spring Framework annotation used to bind an incoming file from a multipart/form-data POST request to a Java MultipartFile object. It enables the handling of file uploads in web applications by providing easy access to the uploaded file's content and metadata.

Java:

@PostMapping("/upload")
public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
// Handle the uploaded file here
return ResponseEntity.ok("Received file: " + file.getOriginalFilename());
}

b. Multiple File Upload

Curl:

curl -X POST "http://localhost:8080/api/upload-multiple" \
-F "files=@/path/to/first-file.txt" \
-F "files=@/path/to/second-file.txt" \
-F "files=@/path/to/third-file.txt"

Java:

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

@RestController
@RequestMapping("/api")
public class MyController {

@PostMapping("/upload-multiple")
public ResponseEntity<String> uploadMultipleFiles(@RequestParam("files")
List<MultipartFile> files) {
// Handle the uploaded files here
StringBuilder response = new StringBuilder("Received files: ");
for (MultipartFile file : files) {
String fileName = file.getOriginalFilename();
// Save or process each file as needed
response.append(fileName).append(", ");
}

return ResponseEntity.ok(response.toString());
}
}

4) Handling Path Parameters

Curl:

curl -X GET "http://localhost:8080/api/resource/123"

In Spring how this request translates to is presented below:

@PathVariableis used in Spring boot for this type of handling

It is a Spring Framework annotation used in Java to extract values from the URL path of a web request and bind them to method parameters. It allows you to access dynamic values such as IDs or names directly from the URL, enabling flexible and parameterised request handling in your Spring controllers.

Java:

@GetMapping("/resource/{id}")
public ResponseEntity<String> getResourceById(@PathVariable("id") Long id) {
// Handle the GET request with a path parameter here
return ResponseEntity.ok("Received ID: " + id);
}

Wrapping Up

With these annotations and practical examples, you now wield a powerful toolkit for handling various types of requests in Spring Boot. Whether you’re fetching data, sending complex payloads, or managing file uploads, Spring Boot simplifies the process.

Happy coding!

Thank you for reading.

If you find this article useful, hit that clap button and follow me to get more articles on your feed.

You can follow me on Twitter.

https://twitter.com/Chirantar

--

--

No responses yet