How do I retrieve query parameters in a Spring Boot controller?

JavaSpring BootRestSpring Mvc

Java Problem Overview


I am developing a project using Spring Boot. I've a controller which accepts GET requests.

Currently I'm accepting requests to the following kind of URLs:

> http://localhost:8888/user/data/002

but I want to accept requests using query parameters:

> http://localhost:8888/user?data=002

Here's the code of my controller:

@RequestMapping(value="/data/{itemid}", method = RequestMethod.GET)
public @ResponseBody
item getitem(@PathVariable("itemid") String itemid) {	
    item i = itemDao.findOne(itemid);	           
    String itemname = i.getItemname();
    String price = i.getPrice();
	return i;
}

Java Solutions


Solution 1 - Java

Use @RequestParam

@RequestMapping(value="user", method = RequestMethod.GET)
public @ResponseBody Item getItem(@RequestParam("data") String itemid){

    Item i = itemDao.findOne(itemid);              
    String itemName = i.getItemName();
    String price = i.getPrice();
    return i;
}

Solution 2 - Java

While the accepted answer by afraisse is absolutely correct in terms of using @RequestParam, I would further suggest to use an Optional<> as you cannot always ensure the right parameter is used. Also, if you need an Integer or Long just use that data type to avoid casting types later on in the DAO.

@RequestMapping(value="/data", method = RequestMethod.GET)
public @ResponseBody
Item getItem(@RequestParam("itemid") Optional<Integer> itemid) { 
    if( itemid.isPresent()){
         Item i = itemDao.findOne(itemid.get());              
         return i;
     } else ....
}

Solution 3 - Java

To accept both @PathVariable and @RequestParam in the same /user endpoint:

@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
                 @RequestParam(required=false) Map<String,String> qparams) {
    qparams.forEach((a,b) -> {
        System.out.println(String.format("%s -> %s",a,b));
    }
  
    if (data != null) {
        System.out.println(data);
    }
}

Testing with curl:

Solution 4 - Java

In Spring boot: 2.1.6, you can use like below:

    @GetMapping("/orders")
	@ApiOperation(value = "retrieve orders", response = OrderResponse.class, responseContainer = "List")
	public List<OrderResponse> getOrders(
			@RequestParam(value = "creationDateTimeFrom", required = true) String creationDateTimeFrom,
			@RequestParam(value = "creationDateTimeTo", required = true) String creationDateTimeTo,
			@RequestParam(value = "location_id", required = true) String location_id) {

		// TODO...

		return response;

@ApiOperation is an annotation that comes from Swagger api, It is used for documenting the apis.

Solution 5 - Java

To accept both Path Variable and query Param in the same endpoint:

@RequestMapping(value = "/hello/{name}", method = RequestMethod.POST)
	public String sayHi(
			@PathVariable("name") String name, 
			@RequestBody Topic topic,
			//@RequestParam(required = false, name = "s") String s, 
			@RequestParam Map<String, String> req) {
		
		return "Hi "+name +" Topic : "+ topic+" RequestParams : "+req;
	}

URL looks like : http://localhost:8080/hello/testUser?city=Pune&Pin=411058&state=Maha

Solution 6 - Java

I was interested in this as well and came across some examples on the Spring Boot site.

   // get with query string parameters e.g. /system/resource?id="rtze1cd2"&person="sam smith" 
// so below the first query parameter id is the variable and name is the variable
// id is shown below as a RequestParam
	@GetMapping("/system/resource")
	// this is for swagger docs
	@ApiOperation(value = "Get the resource identified by id and person")
	ResponseEntity<?> getSomeResourceWithParameters(@RequestParam String id, @RequestParam("person") String name) {
	
		InterestingResource resource = getMyInterestingResourc(id, name);
		logger.info("Request to get an id of "+id+" with a name of person: "+name);
		
		return new ResponseEntity<Object>(resource, HttpStatus.OK);
	}

See here also

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMehandi HassanView Question on Stackoverflow
Solution 1 - JavaafraisseView Answer on Stackoverflow
Solution 2 - JavaAndrew GrotheView Answer on Stackoverflow
Solution 3 - JavaeigenfieldView Answer on Stackoverflow
Solution 4 - JavaShashankView Answer on Stackoverflow
Solution 5 - Javasatish guptaView Answer on Stackoverflow
Solution 6 - JavaTKPhillyBurbView Answer on Stackoverflow