Monday, November 18, 2024
Google search engine
HomeLanguagesJavaSpring – MVC RequestParam Annotation

Spring – MVC RequestParam Annotation

@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'
}

 

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments