0Pricing
Spring Boot 4 Complete Guide · Lezione

Gestire richieste e risposte HTTP

Impari a elaborare parametri delle richieste, variabili del percorso e corpi delle richieste, creando risposte HTTP appropriate

Gestire richieste e risposte HTTP è una lezione Spring Boot 4 Complete Guide gratuita su CoddyKit. Questa è la lezione 2 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento Spring Boot 4 Complete Guide, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso Spring Boot 4 Complete Guide include 4 lezioni in totale.

Parti di questa lezione non sono ancora state tradotte e vengono mostrate in inglese.

Requests & Responses

When you interact with a web application, your browser sends an HTTP Request to a server. The server then processes it and sends back an HTTP Response.

In Spring Boot, we write code to listen for these requests, extract information, perform actions, and then craft a suitable response.

Getting Query Params: @RequestParam

Sometimes, extra data is sent in the URL after a ?, like /search?keyword=java. These are query parameters.

Spring Boot uses the @RequestParam annotation to easily extract these values into your method parameters.

Live Demo: @RequestParam

Try running this example. After the app starts, open your browser or a tool like Postman and visit http://localhost:8080/hello?name=Coddy. See what happens!

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class Main {

  public static void main(String[] args) {
    SpringApplication.run(Main.class, args);
  }

  @GetMapping("/hello")
  public String sayHello(
      @RequestParam(defaultValue = "Guest") String name) {
    return "Hello, " + name + "!";
  }
}

Extracting from Path: @PathVariable

Other times, important data is part of the URL path itself, like /users/123. Here, 123 is an ID.

The @PathVariable annotation lets you capture these dynamic segments from the URL directly into your method parameters.

Live Demo: @PathVariable

Run this app, then visit http://localhost:8080/items/apple or http://localhost:8080/items/banana in your browser.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class Main {

  public static void main(String[] args) {
    SpringApplication.run(Main.class, args);
  }

  @GetMapping("/items/{itemName}")
  public String getItemDetails(@PathVariable String itemName) {
    return "You requested item: " + itemName;
  }
}

Query vs. Path: When to Use?

  • @RequestParam: Use for optional filtering, sorting, or pagination (e.g., /products?category=books&page=1).
  • @PathVariable: Use for identifying a specific resource (e.g., /users/{id}, /products/{sku}). It's essential for the resource's identity.

Handling Data Payloads: @RequestBody

For operations like creating or updating resources (POST, PUT requests), clients often send complex data (like JSON or XML) in the request body.

The @RequestBody annotation automatically converts this body content into a Java object for you, thanks to Spring's built-in message converters.

Live Demo: @RequestBody

Run this. Use a tool like Postman to send a POST request to http://localhost:8080/users with a JSON body:

{"id":1, "name":"Coddy"}

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class Main {

  public static void main(String[] args) {
    SpringApplication.run(Main.class, args);
  }

  // Define a simple User class
  public static class User {
    private Long id;
    private String name;

    // Getters and setters for JSON mapping
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
  }

  @PostMapping("/users")
  public String createUser(@RequestBody User user) {
    return "User created: ID=" + user.getId() +
           ", Name=" + user.getName();
  }
}

Custom Responses: ResponseEntity

By default, Spring often returns a String or a Java object, which Spring converts to JSON/XML with a 200 OK status.

For more control, especially over HTTP status codes (like 201 Created, 404 Not Found), use ResponseEntity. It lets you specify the body, status, and headers explicitly.

Quick Check: Request Handling

Consider a Spring Boot REST endpoint designed to fetch a user by their unique ID, like /api/users/5. Which annotation is best suited to extract the 5 from the URL?

Lesson Summary

We've covered how Spring Boot makes handling HTTP requests easy:

  • @RequestParam for query parameters (optional data).
  • @PathVariable for path variables (resource identifiers).
  • @RequestBody for deserializing request body content into Java objects.
  • ResponseEntity for fine-grained control over HTTP responses, including status codes.

Mastering these annotations is key to building robust RESTful APIs!

Domande Frequenti

La lezione «Gestire richieste e risposte HTTP» è gratuita?

Sì — il testo completo di «Gestire richieste e risposte HTTP» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso Spring Boot 4 Complete Guide, passa a CoddyKit PRO. Il corso Spring Boot 4 Complete Guide include 4 lezioni in totale.

Cosa imparerò in «Gestire richieste e risposte HTTP»?

Impari a elaborare parametri delle richieste, variabili del percorso e corpi delle richieste, creando risposte HTTP appropriate Eserciti Spring Boot 4 Complete Guide con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare Spring Boot 4 Complete Guide?

Non è richiesta alcuna esperienza precedente. Spring Boot 4 Complete Guide su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 2 di 4.

Quanto tempo richiede la lezione «Gestire richieste e risposte HTTP»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione Spring Boot 4 Complete Guide?

Sì. Ogni lezione Spring Boot 4 Complete Guide include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Creare controller REST
  2. Gestire richieste e risposte HTTP
  3. Validazione degli input e gestione degli errori
  4. Documentare le REST API con OpenAPI e Swagger
← Torna a Spring Boot 4 Complete Guide