In this article, we will see how to use the defaultValue with RequestParam values.

In many web frameworks, including Spring MVC for Java, we can define request parameters that are expected to be part of a request. We can set a default value that is used when the parameter is missing in the request.

Let us first understand what is @RequestParam in Spring MVC. In Spring MVC, we use requestParam to bind a request parameter to a method parameter in a controller method and specify the expected parameter name, whether the parameter is required or not, and what its default value is.

Following is an example:

@GetMapping("/example")
public String example(@RequestParam(name = "param", required = false, defaultValue = "default") String param) {
    // Controller logic
}

In the above example, the controller method expects a request parameter named “param”, and the required attribute is set to false, which means that the parameter is optional and the defaultValue of “default” will be used if the parameter “param” is not present in the request.

There is a significant difference between handling a parameter whose value is missing and a parameter whose value is empty.

Missing parameter vs empty value in Request params

An missing parameter refers to a parameter which is expected but is not present in the URL query string, form data, or any other part of the request, the defaultValue will be used if provided, or the parameter will be set to null if no defaultValue is specified.

An empty value refers to a parameter that is present in the request, but its value is an empty string (“”). This usually happens when we submit a form with a text input field left blank. In this case, the parameter is not missing but it has an empty value.

Can defaultValue handle the empty values in a request?

The defaultValue attribute in @RequestParam is used to handle missing parameters but not parameters with empty values. If a parameter is present in the request but has an empty value, the defaultValue will not be used. Instead, the parameter will be bound to the empty string.

To handle parameters with empty values and provide a default value we would need to implement custom logic within our own controller method.

For example, you can check if the parameter is an empty string and, if so, assign it the default value manually. See the following example for more information

@GetMapping("/example")
public String example(@RequestParam(name = "param", required = false, defaultValue = "default") String param) {
    if (param.isEmpty()) {
        param = "default";
    }
}

Categorized in:

Tagged in: