Spring MVC Tutorial

Core Spring MVC

Spring MVC - Annotation

Spring MVC - Form Handling

Spring MVC with JSTL

Spring MVC with REST API

Spring MVC with Database

How to Make get() Method Request in Java Spring?

In a Spring Boot application, you can use the RestTemplate class or the newer WebClient class to make HTTP GET requests. Both classes are part of Spring's web module and are used to consume web services.

Below are examples demonstrating how to make GET requests using both RestTemplate and WebClient.

Using RestTemplate:

  • Add Dependency: Add Spring Boot Starter Web to your pom.xml:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
  • Code Example: Use RestTemplate to make a GET request:
import org.springframework.web.client.RestTemplate;

public class RestTemplateExample {
    public static void main(String[] args) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://jsonplaceholder.typicode.com/todos/1";

        // For response as String
        String response = restTemplate.getForObject(url, String.class);
        System.out.println("Response: " + response);

        // For response as a mapped object
        Todo todo = restTemplate.getForObject(url, Todo.class);
        System.out.println("Todo Title: " + todo.getTitle());
    }
}

// Define a class to capture the response
class Todo {
    private Long id;
    private String title;
    // getters and setters
}

Using WebClient:

  • Add Dependency: Add Spring Boot Starter WebFlux to your pom.xml:
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
  • Code Example: Use WebClient to make a GET request:
import org.springframework.web.reactive.function.client.WebClient;

public class WebClientExample {
    public static void main(String[] args) {
        WebClient webClient = WebClient.create();
        String url = "https://jsonplaceholder.typicode.com/todos/1";

        // For response as String
        String response = webClient.get()
                .uri(url)
                .retrieve()
                .bodyToMono(String.class)
                .block();
        System.out.println("Response: " + response);

        // For response as a mapped object
        Todo todo = webClient.get()
                .uri(url)
                .retrieve()
                .bodyToMono(Todo.class)
                .block();
        System.out.println("Todo Title: " + todo.getTitle());
    }
}

// Define a class to capture the response
class Todo {
    private Long id;
    private String title;
    // getters and setters
}

In both examples, we've used the free JSONPlaceholder API, and the response is either captured as a String or as a mapped Todo object.

Feel free to adapt these examples to fit the specific needs of your application.

  1. Spring MVC GET request example:

    Description: Handling a GET request in Spring MVC involves creating a controller method annotated with @GetMapping and specifying the resource to retrieve.

    Code snippet (Java):

    @Controller
    @RequestMapping("/api")
    public class ApiController {
    
        @GetMapping("/get/{id}")
        public ResponseEntity<String> getResource(@PathVariable Long id) {
            // Logic to retrieve the resource with the given id
            // ...
    
            return ResponseEntity.ok("Resource retrieved successfully");
        }
    }
    
  2. RestTemplate GET request in Spring:

    Description: Making a GET request using RestTemplate involves using the getForObject() method and specifying the URL and any path variables.

    Code snippet (Java):

    RestTemplate restTemplate = new RestTemplate();
    
    String url = "http://localhost:8080/api/get/{id}";
    String response = restTemplate.getForObject(url, String.class, 123L);
    
  3. Spring WebClient GET example:

    Description: Using WebClient for GET requests involves creating a WebClient instance and using the get() method.

    Code snippet (Java):

    WebClient webClient = WebClient.create("http://localhost:8080");
    
    String response = webClient
        .get()
        .uri("/api/get/{id}", 456L)
        .retrieve()
        .bodyToMono(String.class)
        .block();
    
  4. Get mapping in Spring Controller:

    Description: Using @GetMapping annotation in a Spring Controller provides a convenient way to handle GET requests for a specific mapping.

    Code snippet (Java):

    @Controller
    @RequestMapping("/resources")
    public class ResourceController {
    
        @GetMapping("/get/{id}")
        public ResponseEntity<String> getResource(@PathVariable Long id) {
            // Logic to retrieve the resource with the given id
            // ...
    
            return ResponseEntity.ok("Resource retrieved successfully");
        }
    }
    
  5. Spring Data JPA find method:

    Description: Spring Data JPA provides a convenient way to retrieve entities using the findById() method.

    Code snippet (Java):

    public interface ResourceRepository extends JpaRepository<Resource, Long> {
        // Spring Data JPA automatically generates findById method
    }
    

    Usage:

    Optional<Resource> resource = resourceRepository.findById(789L);
    
  6. HTTP GET request in Spring Rest API:

    Description: Handling a GET request in a Spring Rest API involves using @GetMapping in a controller method.

    Code snippet (Java):

    @RestController
    @RequestMapping("/api")
    public class ApiController {
    
        @GetMapping("/get/{id}")
        public ResponseEntity<String> getResource(@PathVariable Long id) {
            // Logic to retrieve the resource with the given id
            // ...
    
            return ResponseEntity.ok("Resource retrieved successfully");
        }
    }
    
  7. Spring MVC get request with PathVariable:

    Description: Handling a GET request in Spring MVC with a PathVariable involves specifying the path variable in the @GetMapping annotation.

    Code snippet (Java):

    @Controller
    @RequestMapping("/resources")
    public class ResourceController {
    
        @GetMapping("/get/{id}")
        public ResponseEntity<String> getResource(@PathVariable Long id) {
            // Logic to retrieve the resource with the given id
            // ...
    
            return ResponseEntity.ok("Resource retrieved successfully");
        }
    }
    
  8. RestAssured GET request in Spring Boot:

    Description: Using RestAssured for GET requests in Spring Boot involves specifying the URL and path variables.

    Code snippet (Java):

    RestAssured.baseURI = "http://localhost:8080";
    
    String response = given()
        .pathParam("id", 987)
    .when()
        .get("/api/get/{id}")
    .then()
        .extract()
        .asString();
    
  9. Spring GET request with RequestMapping:

    Description: Handling a GET request in Spring with @RequestMapping involves specifying the method as GET and the path.

    Code snippet (Java):

    @Controller
    @RequestMapping("/api")
    public class ApiController {
    
        @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
        public ResponseEntity<String> getResource(@PathVariable Long id) {
            // Logic to retrieve the resource with the given id
            // ...
    
            return ResponseEntity.ok("Resource retrieved successfully");
        }
    }