The Wayback Machine - https://web.archive.org/web/20240913150449/https://www.geeksforgeeks.org/spring-rest-controller/
Open In App

Spring – REST Controller

Last Updated : 26 Nov, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Previous Article
Next Article

Similar Reads

Create and Run Your First Spring MVC Controller in Eclipse/Spring Tool Suite
Spring MVC framework enables separation of modules namely Model, View, and Controller, and seamlessly handles the application integration. This enables the developer to create complex applications also using plain java classes. The model object can be passed between view and controller using maps. In this article, we will see how to set up a Spring
5 min read
Spring @Controller Annotation with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
4 min read
Spring - Multi Action Controller with Example
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier t
5 min read
Spring MVC - Multiple Controller
We may construct numerous controllers at once in Spring MVC. Each controller class must be annotated with the @Controller annotation. A Spring MVC example with numerous controllers can be found here. The procedure is as follows: In the case of Maven, load the spring jar files or add dependencies.Make your controller class.Provide a controller entry
2 min read
Difference Between @Component, @Repository, @Service, and @Controller Annotations in Spring
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. Here, we are going to discuss the difference between the 4 most im
4 min read
Difference Between @Controller and @RestController Annotation in Spring
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. @Controller Annotation: Spring @Controller annotation is also a sp
3 min read
Difference Between @Controller and @Service Annotation in Spring
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. Spring @Controller AnnotationSpring @Controller annotation is a sp
5 min read
Produce XML Response with Spring WebMVC Controller
In this article, we will explore the mechanisms and aspects of Spring WebMVC – producing XML responses with controllers. And also guides Java developers through the steps of configuring a Spring WebMVC controller to produce XML responses. There are three main approaches to configuring Spring MVC controllers to produce XML responses: JAXB Marshallin
3 min read
Spring MVC - Download File Controller
The Spring MVC is an approach for designing and developing the web application in the MVC pattern. In this article, we will learn how to develop logic for downloading a file from the server or file location in the Spring Boot with Spring Controller. For the application, we have used one HTML page, Spring Boot with MVC Pattern. We will explain from
4 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code &lt;?xml version=&quot;1.0&quot; encoding=
4 min read
Difference Between Spring DAO vs Spring ORM vs Spring JDBC
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring-DAO Spring-DAO is not a spring module. It does not provide interfaces or templates
5 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
Spring MVC - Get Probability of a Gender by Providing a Name using REST API
A lot of funful REST API calls are available as open source. Suppose if we like to keep a name to our nears and dears, we can just check that by means of a REST API call and get the gender, what is the probability of being that gender and how many times does it come with it? Relevant REST API call https://api.genderize.io?name=&lt;Provide your desi
7 min read
How to create a REST API using Java Spring Boot
Representational state transfer (REST) is a software architectural style that defines a set of constraints to be used for creating Web services. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer systems on the Internet. RESTful Web services allow the requesting systems
6 min read
JSON using Jackson in REST API Implementation with Spring Boot
Whenever we are implementing a REST API with Spring (Spring Boot), we would have come across the requirement to exclude NULLs in the JSON Response of the API. Also, there might be a requirement to externalize turning ON/OFF this feature: Exclude NULLS in the JSON Response, thereby allowing the consumer of the API to customize as per the need. In th
3 min read
Spring MVC - Get Exchange Rate Values using REST API
People are doing business, and developing software for geographical locations. That means the calculation of a software price will vary globally. During those scenarios, we need to know about the exchange rates for a given currency. Nowadays many open source REST API calls are available and among that there is a call available to get exchange rates
5 min read
Spring Boot - REST Example
We all know in today's world, most web app follows the client-server architecture. The app itself is the client or frontend part under the hood it needs to call the server or the backend to get or save the data this communication happens using HTTP protocol the same protocol is the power of the web. On the server, we expose the bunch of services th
4 min read
Spring - REST JSON Response
REST APIs are becoming popular for the advantages they provide in the development of applications. REST APIs work like a client-server architecture. The client makes a request and a server (REST API) responds back by providing some kind of data. A client can be any front-end framework like Angular, React, etc, or Spring application ( internal/exter
6 min read
Spring - REST XML Response
The popularity of REST API is increasing day by day as it fulfills architecting an application in a convenient manner. A REST API is an acronym for 'Representational state transfer'. It is also called RESTful web services. It is also a 'Controller', but with a difference that Rest Controller returns Data, while Controller returns a View of 'Model-V
7 min read
Spring - REST Pagination
Spring Framework is built on top of servlets. This particular web framework comes with very essential features with which we can develop efficient and effective web applications. On top of Spring Framework, Spring Boot was released in April 2014. The main aim behind the Spring Boot was the feature of Auto-Configuration. Spring MVC ( Model View Cont
6 min read
How to Extract TV Show Details via REST API and Spring MVC?
REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. Spring MVC is a Web MVC Framework for building web applications. It is a spring module same as spring boot, s
9 min read
OpenSource REST API URL and Retrieving Data From it By Using Spring MVC
In this internet era, a lot of helper services are available in the form of REST API and mostly REST API provides us the details in the form of JSON/XML. We can use them in our applications and render the data as we like. Here is the list of a few opensource REST API URLs: API NameDescriptionURLCoinGeckoExchange rates https://api.coingecko.com/api/
6 min read
Spring MVC - Get University/College Details via REST API
REpresentational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. Spring MVC is a Web MVC Framework for building web applications. It is a spring module same as spring boot, s
6 min read
Spring MVC - Getting Cryptocurrency Details using REST API
Cryptocurrencies are a hot topic throughout the world. Trading with cryptocurrency got both pros and cons. Nowadays REST APIs are very useful to get much information including cryptocurrencies. In this article, we are going to see about one such REST API call to get cryptocurrency detail. We are going to retrieve the information by using Spring MVC
5 min read
Get Time Zone by Providing Latitude and Longitude using Spring MVC and REST API
Spring MVC Framework follows the Model-View-Controller design pattern. It is used to develop web applications. It works around DispatcherServlet. DispatcherServlet handles all the HTTP requests and responses. In this article, we are going to see about a REST API call to find the coordinates for the given latitude and longitude. Each and every area
6 min read
Spring MVC - Comparison of Cryptocurrencies using REST API
REST APIS is available in plenty nowadays. As cryptocurrencies are a hot topic nowadays, there is always a need to compare the different cryptocurrencies and get the corresponding value in different currencies. As a sample, let us take a REST API call as https://min-api.cryptocompare.com/data/price?fsym=LTC&amp;tsyms=BTC,USD,EUR,INR Here fym repres
6 min read
Spring MVC - Last 24 Hour Cryptocurrency Data using REST API
Cryptocurrencies are a hot topic now and in the future; they may also be a payment source. Hence a lot of research is getting done. Many REST APIs are available to provide data in JSON format. We are going to see one such REST API as https://api.wazirx.com/sapi/v1/ticker/24hr?symbol=&lt;Need to provide the symbol of cryptocurrency&gt; Example: http
5 min read
Spring MVC Project - Retrieving Population, Area and Region Details using Rest API
REST API is more popular nowadays as we can able to get a variety of information like Population, Area, region, sub-region, etc., One such REST API that we are going to see here is https://restcountries.com/v3.1/capital/&lt;any capital of a country&gt; Example: https://restcountries.com/v3.1/capital/delhi Corresponding JSON Response: As a Maven Spr
4 min read
Spring Boot - REST API Documentation using OpenAPI
For any application, API documentation is essential for both users and developers. How to use an API, what will be the request body, and what will the API's response be? API documentation is the answer to all of these questions, springdoc-openapi is a Java library that automates the generation of the API documentation in both JSON/YAML and HTML for
4 min read
What is Spring Data REST?
Spring Data REST is a framework that exposes Spring Data repositories as RESTful endpoints. It allows you to create REST APIs for your data without having to write any controller code. Under the hood, Spring Data REST uses Spring Data repositories to access and manage data. So you first need to define Spring Data repositories for your entities. The
7 min read
Article Tags :
Practice Tags :