The Wayback Machine - https://web.archive.org/web/20240909200150/https://www.geeksforgeeks.org/spring-mvc-requestparam-annotation/
Open In App

Spring – MVC RequestParam Annotation

Last Updated : 09 Mar, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

@RequestParam annotation enables spring to extract input data that may be passed as a query, form data, or any arbitrary custom data. Here, we will see how we can use @RequestParam when building RESTful APIs for a web-based application.  

Context of the Application: Let us suppose we are implementing a sample feature for the ‘Geeksforgeeks’ web application, where users will be able to post and retrieve article topics available to write articles on them. Here we will be using hashmaps as our database for simplicity. We use static block to load default entry into our hashmap/DB. 

Illustration:

static int ID = 1;

// Using hashmaps instead of repository for simplicity
public static Map<Integer, String> articleTopics = new HashMap();
static 
{
    articleTopics.put(0, "GFG");
}

 Simple mapping Using @RequestParam

Let’s say we have an endpoint /api/v1/article which takes a query parameter articleId where users will be able to get the article topic given the article id.  If the given articleId is not present we return “Article not accepted” as a response with 404 Bad Request as status.

Example:

// Java Program to Illustrate Simple GET Mapping

// Annotation
@GetMapping("/api/v1/article")

// Method
public ResponseEntity<String>
getArticleTopic(@RequestParam Integer articleId) 
{

    if (articleTopics.containsKey(articleId)) 
    {
        return ResponseEntity.ok(
                   articleId + " " + articleTopics.get(articleId));
    }

    return ResponseEntity.badRequest().body(
               "Article doesnot exists");
}

Note:

  • Static blocks executes automatically when the class is loaded in memory.
  • Annotation @GetMapping is used for mapping HTTP GET requests for specific handler methods.
  • ResponseEntity represents an HTTP response which includes headers, body and status.
  • Postman is used for testing the APIs.

When we tried to get the article already present in our database, we get the required response body with ‘200 OK’ as status code.

When we tried to get the article not present in our database, we get the “Article not present” response body with 400 BAD REQUEST as status code.

 

Specifying the Request Parameter Name Using @RequestParam

Let’s say we have an endpoint /api/v2/article for posting article topics which takes a query parameter articleName as name.

Example

// Specifying the request parameter name

// Annotation 
@PostMapping("api/v2/article")
public ResponseEntity<String> postArticleTopic(@RequestParam("name") String articleName) 
{
    if (articleTopics.containsValue(articleName)) 
    {
        return ResponseEntity.badRequest().body("Article already exists");
    }

    int currentArticleID = ID++;
    articleTopics.put(currentArticleID, articleName);
    return ResponseEntity.ok("Saved : [" + currentArticleID + "," + 
                            articleTopics.get(currentArticleID) + "]");
}

When we tried to get the article doesn’t exist in our database, we save the request and return a response with 200 OK as status code.

When we tried to get the article already present in our database, we get the “Article already exists” response body with 400 BAD REQUEST as status code.

Using @RequestParam with Default Value

Let’s say we have an endpoint /api/v3/article for getting article topics which takes a query parameter articleId. Here we have used defaultValue attribute which takes the default value if no value is provided.

Example:

// Default value for Request Parameters

@GetMapping("/api/v3/article")
public ResponseEntity<String> getArticleTopicOrDefault(@RequestParam(defaultValue = "0")Integer articleId) {
    if (!articleTopics.containsKey(articleId)) 
    {
        // If the provided articleId is not present in Database, then also return default
        articleId = 0;
    }
    // If no value is provided for id then return default
    return ResponseEntity.ok(articleId + " " + articleTopics.get(articleId));
}

If no value is provided for the query parameter, then return the default value.

If the value provided doesn’t exist in the database, then also return the default value.

Using @RequestParam For Mapping Multiple Value Query Parameter

Let’s say we have an endpoint /api/v4/article for posting article topics which takes a list as a query parameter. 

Example

// Mapping a multivalue parameter

@PostMapping("/api/v4/article")

public ResponseEntity<String> getMultipleArticleTopics(@RequestParam List<String> names) 
{
    for (String topic : names) 
    {
        articleTopics.put(ID++, topic);
    }
    return ResponseEntity.accepted().body("Saved : " + names);
}

Implementation:

Java




// Java Program to Illustrate Spring - MVC
// RequestParam Annotation
 
package com.example.springmvc.RequestParamAnnotation;
 
// Importing required classes
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
// Annotation
@RestController
 
// Class
public class Controller {
    static int ID = 1;
 
    // Using hashmaps instead of repository for simplicity
    public static Map<Integer, String> articleTopics
        = new HashMap();
    static { articleTopics.put(0, "GFG"); }
 
    // Simple mapping
    @GetMapping("/api/v1/article")
 
    public ResponseEntity<String>
    getArticleTopic(@RequestParam Integer articleId)
    {
 
        // Searching in map if not found return null;
        if (articleTopics.containsKey(articleId)) {
 
            return ResponseEntity.ok(
                articleId + " "
                + articleTopics.get(articleId));
        }
 
        return ResponseEntity.badRequest().body(
            "Article doesnot exists");
    }
 
    // Specifying the request parameter name
    @PostMapping("api/v2/article")
 
    public ResponseEntity<String> postArticleTopic(
        @RequestParam("name") String articleName)
    {
        if (articleTopics.containsValue(articleName)) {
 
            return ResponseEntity.badRequest().body(
                "Article already exists");
        }
 
        int currentArticleID = ID++;
        articleTopics.put(currentArticleID, articleName);
 
        return ResponseEntity.ok(
            "Saved : [" + currentArticleID + ","
            + articleTopics.get(currentArticleID) + "]");
    }
 
    // Default value for Request Parameters
    @GetMapping("/api/v3/article")
 
    public ResponseEntity<String> getArticleTopicOrDefault(
        @RequestParam(defaultValue = "0") Integer articleId)
    {
        if (!articleTopics.containsKey(articleId)) {
 
            // If the provided articleId is not present in
            // DB, then also return default
            articleId = 0;
        }
 
        // If no value is provided for ID
        // then return default
        return ResponseEntity.ok(
            articleId + " " + articleTopics.get(articleId));
    }
 
    // Mapping a multivalue Container
    r @PostMapping("/api/v4/article")
    public ResponseEntity<String> getMultipleArticleTopics(
        @RequestParam List<String> names)
    {
        for (String topic : names) {
            articleTopics.put(ID++, topic);
        }
 
        return ResponseEntity.accepted().body("Saved : "
                                              + names);
    }
}


 
 

Note : @RestController is a convenience annotation used for creating Restful controllers.

 

Dependencies: Gradle

 

dependencies 
{
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'javax.validation:validation-api:2.0.1.Final'
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

 



Previous Article
Next Article

Similar Reads

How to Capture Data using @RequestParam Annotation in Spring?
@RequestParam annotation enables spring to capture input data that may be passed as a query, form data, or any arbitrary custom data. It is used to bind a web request parameter to a method parameter. Here we are going to understand these two above lines and we will see how can we capture data using this annotation. Let's create a simple MVC applica
7 min read
Spring Boot - @PathVariable and @RequestParam Annotations
When building RESTful APIs with Spring Boot, it's crucial to extract data from incoming HTTP requests to process and respond accordingly. The Spring framework provides two main annotations for this purpose: @PathVariable and @RequestParam. The @PathVariable annotation is used to retrieve data from the URL path. By defining placeholders in the reque
8 min read
Spring Boot - Difference Between @Service Annotation and @Repository Annotation
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. @Service Annotation In an application, the business logic resides
7 min read
Working with Cookies in Spring MVC using @CookieValue Annotation
Cookies are the concept of storing user information on the client side in the form of a text file. In this text file lot of information is available about clients or users. Cookies are small pieces of data that are sent by the web servers to the user's web browsers and those cookies are stored in the client only, the cookies play an important role
8 min read
Spring MVC @SessionAttributes Annotation with Example
In the ever-evolving world of web development, a constant challenge is to seamlessly manage data between requests. Enter Spring MVC's @SessionAttributes annotation, a powerful solution that elegantly manages the session attributes of a Spring application. This markup becomes a lifesaver when certain information must persist throughout the interacti
3 min read
Spring MVC context:annotation-config VS context:component-scan
In this article, we will learn about Spring MVC &lt;context:annotation-config&gt; vs &lt;context:component-scan&gt;. Activating all annotations existing in Java beans that have already been registered either by definition in an application context file or by component scanning is the primary function of annotation-config. The requirement for regist
3 min read
Spring MVC @ModelAttribute Annotation with Example
In Spring MVC, the @ModelAttribute annotation binds a method parameter or method return value to a named model attribute and then exposes it to a web view. It refers to the property of the Model object. For example, if we have a form with a form backing object that is called "Student" then we can have Spring MVC supply this object to a Controller m
8 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
Difference between @RequestBody and @RequestParam
In Spring Boot, the @RequestBody is used for binding the HTTP request body to a parameter in a controller method and it is typically used when we expect the client to send data in the request body when submitting a form or sending JSON data. The @RequestParam is one of the powerful full annotations in Spring Boot. This annotation can enable the Spr
5 min read
Difference between Spring MVC and Spring Boot
1. Spring MVC : Spring is widely used for creating scalable applications. For web applications Spring provides Spring MVC framework which is a widely used module of spring which is used to create scalable web applications. Spring MVC framework enables the separation of modules namely Model View, Controller, and seamlessly handles the application in
3 min read
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
Difference Between Spring MVC and Spring WebFlux
Spring MVCSpring MVC Framework takes on the Model-View-Controller design pattern, which moves around the Dispatcher Servlet, also called the Front Controller. With the help of annotations like @Controller and @RequestMapping, the by-default handler becomes a robust(strong) tool with a diverse set of handling ways. This kind of dynamic kind of featu
5 min read
Spring MVC vs Spring Web Flux: Top Differences
For creating Java-based projects and applications, developers usually have to choose between Spring MVC and Spring WebFlux when using the Spring framework to create web apps. To pick the best framework for their project, developers need to know how each one is different and what features they have. Each framework has its own benefits compared to th
11 min read
How to Build a RESTful API with Spring Boot and Spring MVC?
RESTful APIs have become the standard for building scalable and maintainable web services in web development. REST (Representational State Transfer) enables a stateless, client-server architecture where resources are accessed via standard HTTP methods. This article demonstrates how to create a RESTful API using Spring Boot and Spring MVC. We will w
7 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 - @PostConstruct and @PreDestroy 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
13 min read
Spring @Autowired Annotation
The @Autowired annotation marks a Constructor, Setter method, Properties and Config() method as to be autowired that is 'injecting beans'(Objects) at runtime by Spring Dependency Injection mechanism which is clearly depicted from the image below as shown: Enabling @Autowired annotation Spring beans can be declared either by Java configuration or XM
3 min read
Spring @Repository 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
5 min read
Spring @Service 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 Data JPA - @Table Annotation
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
3 min read
Spring Data JPA - @Id Annotation
Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence API) is like an interface and the hibernate is the implementation of the met
3 min read
Spring Data JPA - @Column Annotation
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
2 min read
Spring Data JPA - Attributes of @Column Annotation with Example
Spring Boot is built on the top of the spring and contains all the features of spring. Spring also provides JPA and hibernate to increase the data manipulation efficiency between the spring application and the database. In very simple terms we can say JPA (Java persistence API) is like an interface and the hibernate is the implementation of the met
3 min read
Spring @ResponseBody Annotation with Example
Spring Annotations allow us to configure dependencies and implement dependency injection through java programs. Those 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. The @ResponseBody annotation tells a c
5 min read
Spring @ComponentScan 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 - Required Annotation
Consider a scenario where a developer wants to make some of the fields as mandatory fields. using the Spring framework, a developer can use the @Required annotation to those fields by pushing the responsibility for such checking onto the container. So container must check whether those fields are being set or not. The Spring Framework supports a nu
7 min read
Spring @Bean Annotation with Example
One of the most important annotations in spring is the @Bean annotation which is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. This annotation is also a part of the spring core framework. So let's understand @Bean Annotation with an
8 min read
Spring AOP - AspectJ Annotation
AOP i.e Aspect-Oriented Programming complements OOP by enabling modularity of cross-cutting concerns. @AspectJ is mainly used for declaring aspects as regular Java classes annotated with annotations. Spring AspectJ AOP implementation has many annotations. They are explained below: @Aspect: It declares the class as an aspect.@Pointcut: It declares t
4 min read
Spring @Configuration Annotation with Example
One of the most important annotations in spring is @Configuration annotation which indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application. This annotation is part of the spring core framework. So let's understand @Configuration Annotation with an examp
4 min read
Spring @RequestMapping Annotation with Example
One of the most important annotations in spring is the @RequestMapping Annotation which is used to map HTTP requests to handler methods of MVC and REST controllers. In Spring MVC applications, the DispatcherServlet (Front Controller) is responsible for routing incoming HTTP requests to handler methods of controllers. When configuring Spring MVC, yo
6 min read