Reading Query String Params – Spring Rest

Suppose in the Web Service URL we decide to pass some parameters like below. Kindly refer the below screenshot from Postman API.

So here we are passing 2 params to the Web Service URL which are name and age. Let’s see how it is handled at the server side by the Spring Rest Controller.

com.techfinanceworld.restapp.controller;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("employees")
public Class EmpController{

@GetMapping
public String getEmployee(@RequestParam(value="name") String name, @RequestParam(value="age") String age) //Line 4
{
   return "Get Employee Was Called with name "+name+ " and age = "+age; //Line 5
}

@PostMapping
public String CreateEmployee()
{
      return "Create Employee Was Called";
}

}

If you see line 4, we make use of the @RequestParam annotation to fetch the parameters passed in the url and assign it to two variables which are name and age.

Now suppose, in the url we don’t pass one parameter. For example the url is

http://localhost:8080/employees?name=John

Then the getEmployee method in the controller class would fail saying that one param is missing.

So how to handle this? Let’s see the below example.

@RestController
@RequestMapping("employees")
public Class EmpController{

@GetMapping
public String getEmployee(@RequestParam(value="name",defaultValue="James") String name, @RequestParam(value="age",defaultValue="Gosling") String age) //Line 4
{
   return "Get Employee Was Called with name "+name+ " and age = "+age; //Line 5
}

@PostMapping
public String CreateEmployee()
{
      return "Create Employee Was Called";
}

}

If ou see line 4, we have introduced a defaultValue property to assign the default value incase the parameter is not passed in the url.

Another way to handle such a scenario is to use required clause.

public String getEmployee(@RequestParam(value="name",required = false) String name, @RequestParam(value="age",required = false) String age)
{
   return "Get Employee Was Called with name "+name+ " and age = "+age; 
}

required = false means the param is not required to be passed and the method can complete successfully without it ebing passed.

*Imp note: Don’t use required = false with a primitive type like int. It would give an exception since an int has to be initialized to a value. We used string above so it will set to null which would not be a problem.