Create Project with Spring Web Dependency
Directory Structure:
pom.xml
4.0.0
org.springframework.boot
spring-boot-starter-parent
3.4.5
com.example
QueryParam
0.0.1-SNAPSHOT
QueryParam
Demo project for Spring Boot
17
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
org.springframework.boot
spring-boot-maven-plugin
GreetingController
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
@GetMapping("/greet")
public String greetUser(@RequestParam String name,@RequestParam(required = false,defaultValue = "User")String title) {
return "Hello "+title+" "+name+"!";
}
}
Hit the Endpoint
URL with Query Parameters:
http://localhost:8080/greet?name=John&title=Mr
Output
Hello Mr John!
Explanation
@RequestParam String name: Marks name as a required query parameter.
@RequestParam(required = false, defaultValue = "User") String title: Makes title optional and assigns a default value if not provided.