Explain Codes LogoExplain Codes Logo

Is it possible to have empty RequestParam values use the defaultValue?

java
request-parameter
spring-annotations
null-pointer-exception
Nikita BarsukovbyNikita Barsukov·Feb 24, 2025
TLDR
@GetMapping("/example") public String handleRequest( @RequestParam(defaultValue = "default") String param) { return "Param is: " + param; }

Here, Spring's @RequestParam is implemented with a defaultValue attribute. This ensures a fallback option when the request parameter is empty, ensuring your application is safeguarded against null values.

Guard against null and blank parameters

In some cases, we might unexpectedly receive null or empty strings as parameters. This can cause a NumberFormatException, especially when dealing with numeric types. To gracefully handle these edge cases, we can assign the @RequestParam to a String type and parse it manually.

Safeguarding against type mismatch

@GetMapping("/example") public String handleNumericRequest( @RequestParam(required = false) String param) { // Who needs a calculator when we have Java! Integer numericValue = (param != null && !param.isEmpty()) ? Integer.parseInt(param) : 42; return "Numeric value is: " + numericValue; }

In the example above, it's ensured that param is non-null and non-blank before trying to parse it. If it doesn't pass these checks, we conveniently set it to the well-known number 42, bypassing any NumberFormatException.

Embrace Spring updates

Spring version 3.2.2 onwards does this heavy lifting for us. The framework intelligently uses the defaultValue for empty parameters making your code tidy and efficient.

Compatibility across Spring versions

Consider using @Nullable annotation. It clarifies your intent and aids compatibility with different Spring versions. Moreover, preventing empty parameters on the client side saves us from many unwanted surprises.

Exploring edge cases and alternatives

Enforce client-side validation

Trimming the problem at its root, ensure front-end validation prevents empty inputs from being sent, prompting the user to fill valid inputs beforehand.

Use type conversion service

A custom type conversion service in Spring could be just what you need. This service translates empty request parameter strings to null values or appropriate defaults for various data types.

Embrace global fallback configuration

When you have common default values across endpoints, configuring a global fallback removes redundancy, making your code DRY and easy to maintain.

Stay updated with documentation

Stay enlightened about issues like SPR-10180 and keep an eye on the Spring documentation. This helps you remain updated about the changes in how @RequestParam behaves across different versions.