How to use @RequestParam annotation in Spring Boot Controller.

In this tutorial, we are going to use the @RequestParam annotation to read request param from request in the controller. Whether it is REST request or non REST request. @RequestParam plays key role in taking input from user or client.

@RequestParam annotation code snippet.


@Target(value=PARAMETER)
 @Retention(value=RUNTIME)
 @Documented
public @interface RequestParam

Annotation which indicates that a method parameter should be bound to a web request parameter.

If the method parameter type is Map and a request parameter name is specified, then the request parameter value is converted to a Map assuming an appropriate conversion strategy is available.

If the method parameter is Map<String, String> or MultiValueMap<String, String> and a parameter name is not specified, then the map parameter is populated with all request parameter names and values.

Example:-

We will create one simple example with one single cotroller. Here we will reuse our mustache helloworld example.

which we have published at below location.

https://medium.com/techwasti/spring-boot-mustache-hello-world-example-ded94471577c

build.gradle

plugins {
	id 'org.springframework.boot' version '2.4.1'
	id 'io.spring.dependency-management' version '1.0.10.RELEASE'
	id 'java'
}

group = 'com.techwasti.mustache'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-mustache'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
	useJUnitPlatform()
}

In the the gradle build file we have the spring-boot-starter-web, which is a starter for building web applications using Spring MVC. It uses Tomcat as the default embedded container. The spring-boot-devtools is an artifact useful when developing Spring Boot applications; it allows automatic restart or live reload of applications. The application is packaged into a JAR file.

HelloController.java:

package com.techwasti.springmustacheex;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HelloController {
    
    @GetMapping(value = {"/", "/hello"})
    public String greetMessage(Model model) {

        String helloworld="Hello and welcome to mustache";

        model.addAttribute("message", helloworld);

        return "hello";
    }
// this is we have added to demonstrate the @RequestParam annotation.
    @RequestMapping(path="/greeting", produces=MediaType.TEXT_PLAIN_VALUE)
    @ResponseBody
    public String greetUser(@RequestParam(defaultValue="GuestUser") String name,
                              @RequestParam(required = false) String adult) {

        var greet = "on".equals(adult) ? "Good morning" : "Hi";

        return String.format("%s %s!", greet, name);
    }
}

The HelloController processes the HTML form. It reads two parameters from the request. A controller class is annotated with the @Controller stereotype annotation in Spring.

  @RequestMapping(path="/greeting", produces=MediaType.TEXT_PLAIN_VALUE)
    @ResponseBody

The greetUser() method is mapped to the /greeting path and produces the plain text response. With the @RequestParam annotation, we bind the request parameter to the method variable. We are binding two values from request to two variables name and adult respectively. The defaultValue option gives a default value if the parameter is not available. The required option tells that the parameter is mandatory.

public String greetUser(@RequestParam(defaultValue="GuestUser") String name,@RequestParam(required = false) String adult)

index.html:

The index.html file is the home page. The file is located in the src/main/resources/static folder, where Spring Boot expects static resources such as HTML, javascript, images or CSS files. We have a simple HTML form with input text and check box tags.

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Home page</title>
        <meta charset="UTF-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    </head>
    <body>

        <form action="greeting">

            <div>
                <label>Name:</label>
                <input type="text" name="name">
            </div>

            <div>
                <label><input type="checkbox" name="adult">Adult</label>
            </div>

            <button type="submit">Submit</button>

        </form>
    </body>
</html>

In the index.html we have <form action=”greeting”>, the same mapping we have in our controller to handle this request.

Application class

package com.techwasti.springmustacheex;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringMustacheExApplication {

	public static void main(String[] args) {
		SpringApplication.run(SpringMustacheExApplication.class, args);
	}

}

The @SpringBootApplication annotation enables auto-configuration and component scanning. This is the entry point of your application. Now everything is ready let us go and run the application and enjoy the output.

$ mvn spring-boot:run

This is just introductory tutorial, please play with it and find more insight about this annotation.

Source Code:-

https://github.com/maheshwarLigade/spring-boot-examples
$ git clone https://github.com/maheshwarLigade/spring-boot-examples
$ cd spring-mustache-ex
$ gradle build
$ gradle bootRun

Reference Links:

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/stereotype/Component.html

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestParam.html

More tutorials like this visit below link

https://www.techwasti.com/category/java/