How to retrieve URL and Query parameters in Spring Boot?

Let’s say you want to create a Spring Boot REST API which accepts URL and query parameters.

How do you retrieve those parameters in the code ?

By using

@RequestParam annotation for query parameter

@PathVariable annotation for URL parameter

Here is an example:

	
	@GetMapping("/restService/{urlParameter}")
	public Map<String,String> restService(@PathVariable("urlParameter") String urlParameter,@RequestParam("queryParameter") String queryParameter){
		
		
		Map<String,String> response = new HashMap<>();
		
		response.put("urlParameter", urlParameter);
		
		response.put("queryParameter",queryParameter);
		
		
		return response;
		
	}

The above method is a GET REST service which takes in a url parameter after the relative path “restService” and also takes in a query parameter with the key “queryParameter”

The URL parameter is enclosed in braces in the relative path passed to @GetMapping annotation.

The URL parameter is then retrieved using @PathVariable annotation which takes the variable indicated in enclosed braces as a parameter.

The query parameter is not mentioned in the relative path passed to @GetMapping annotation.

Here is a sample GET request:

http://localhost:8080/restService/myURLParameter?queryParameter=myQueryParameter

myURLParameter is the URL parameter

myQueryParameter is the query parameter for the key queryParameter.

The service just returns both the parameters as a JSON.

Here is the output:

That’s it!


Posted

in

by

Comments

Leave a Reply

Discover more from The Full Stack Developer

Subscribe now to keep reading and get access to the full archive.

Continue reading