Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaSpring – REST Controller

Spring – REST Controller

Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework and making a production-ready application in it takes very little time. In this article, we will discuss what is REST controller is in the spring boot. There are mainly two controllers are used in the spring, controller and the second one is RestController with the help of @controller and @restcontroller annotations. The main difference between the @restcontroller and the @controller is that the @restcontroller combination of the @controller and @ResponseBody annotation.

RestController: RestController is used for making restful web services with the help of the @RestController annotation. This annotation is used at the class level and allows the class to handle the requests made by the client. Let’s understand @RestController annotation using an example. The RestController allows to handle all REST APIs such as GET, POST, Delete, PUT requests. 

Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an application using a spring initializer and then use an IDE to create a sample GET route. Therefore, to do this, the following steps are followed sequentially as follows.

Step by Step Implementation

Step 1: Go to Spring Initializr

Fill in the details as per the requirements. For this application:

Project: Maven
Language: Java
Spring Boot: 2.2.8
Packaging: JAR
Java: 8
Dependencies: Spring Web

Step 2: Click on Generate which will download the starter project

Step 3: Extract the zip file. Now open a suitable IDE and then go to File > New > Project from existing sources > Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows:

Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project.

Step 4: Go to src > main > java > com.gfg.Spring.boot.app, create a java class with the name Controller and add the annotation @RestController and other class named as Details.

Details:

Java




public class Details {
  
    // Creating an object of ArrayList
    static ArrayList<Details> Data = new ArrayList<Details>();
    int number;
    String name;
    Details(int number, String name)
    {
        // This keyword refers 
          // to parent instance itself
        this.number = number;
        this.name = name;
    }
}


Controller:

Java




@RestController
// Class
public class Controller {
    // Constructor
    Controller()
    {
        a.add(1);
        a.add(2);
    }
  
    @GetMapping("/hello/{name}/{age}")
    public void insert(@PathVariable("name") String name,
                       @PathVariable("age") int age)
    {
  
        // Print and display name and age
        System.out.println(name);
        System.out.println(age);
    }
  
    // Creating an empty ArrayList
    ArrayList<Integer> a = new ArrayList<>();
  
    // Annotation
    @DeleteMapping("/hello/{id}")
    // Method
    public void deleteById(@PathVariable("id") int id)
    {
        a.remove(new Integer((id)));
        print();
    }
    
       // Handling post request
    @PostMapping("/EnterDetails")
    String insert(@RequestBody Details ob)
    {
        // Storing the incoming data in the list
        Data.add(new Details(ob.number, ob.name));
  
        // Iterating using foreach loop
        for (Details obd : Data) {
            System.out.println(obd.name + " " + ob.number);
        }
        return "Data Inserted";
    }
  
    // Method
    void print()
    {
        for (int elements : a) {
            System.out.print(elements);
        }
}


This application is now ready to run.

Step 5: Run the SpringBootAppApplication class and wait for the Tomcat server to start.

Note: The default port of the Tomcat server is 8080 and can be changed in the application.properties file.

Let’s make a delete request from the postman

Output: As generated on console 

2

This controller.java file is used for handling all incoming requests from the client-side.

RELATED ARTICLES

Most Popular

Recent Comments