Query parameter handling with Spring Boot

In last post, Hello World with Spring Boot we have seen how to create REST service with Spring Boot. Now we will extend the same HelloController to work on query parameters.

Here we will get the "name" as query parameter, and respond with updated message. Update HelloController.java file with below code. 

  
package hello;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String sayHello(@RequestParam(value="name") String name) {
        return  String.format("Hello %s with Spring Boot !!!", name);
    }
}

We have added @RequestParam annotation which will assign value of query parameter 'name' to variable name. Now run you application and hit "http://localhost:8080/hello?name=XYZ" on browser. You should get "Hello XYZ with Spring Boot !!!" in return.
But with this code the "http://localhost:8080/hello" URL will return error "bad request" as query parameter is missing. This is helpful when you want the query parameter as mandatory input.

In order to support optional query parter, you can have default value for parameters as below.
 
package hello;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String sayHello(@RequestParam(value="name", defaultValue="World") String name) {
        return  String.format("Hello %s with Spring Boot !!!", name);
    }
}

'defaultValue' allows the query parameter to be optional. Optional query parameters can be handled using 'required = false' as code below.  'defaultValue' will assign default value to variable 'name', if it's not specified value of 'name' would be null. 


@RestController
public class HelloController {
    @RequestMapping("/hello")
    public String sayHello(@RequestParam(value="name", required = false, defaultValue = "World") String name) {
        return  String.format("Hello %s with Spring Boot !!!", name);
    }
}

No comments:

Post a Comment

Golang: Http POST Request with JSON Body example

Go standard library comes with "net/http" package which has excellent support for HTTP Client and Server.   In order to post JSON ...