Spring Boot
RequestParam
Default Value
Java
MVC

How to give default value as integer in RequestParam

Codemia Knowledge Hub ·

In Java's Spring framework, handling HTTP request parameters is a fundamental part of building web applications. When dealing with optional parameters, providing default values is a common requirement. The `@RequestParam` annotation makes this straightforward, and this article explores how to assign default integer values to request parameters using this annotation.

Understanding `@RequestParam`

`@RequestParam` is an annotation used to extract query parameters, form data, or any custom parameters from a request. It is part of the `org.springframework.web.bind.annotation` package and can be bound to method parameters in a controller class. This annotation is very flexible, supporting various attributes to customize its behavior.

  • `value`: The name of the request parameter to bind to.
  • `required`: A boolean that enables parameter as mandatory or optional. The default is `true`.
  • `defaultValue`: This attribute is used to supply a default value that will be applied if the request parameter is not present or is empty.

When you want to ensure that an integer value is maintained as a parameter, `defaultValue` comes into play efficiently.

Setting a Default Integer Value

To give a default value as an integer, the `@RequestParam` annotation requires a careful approach. Since the annotation deals with request parameters as strings, the `defaultValue` attribute is always defined as a `String`. Thus, when specifying a default integer value, it should be passed as a string and then converted inside the method if necessary.

  • Parameter Definition: The method `exampleMethod` requires a parameter `number`.
  • Default Value: Using `defaultValue = "10"`, the `number` parameter will default to `10` if not specified in the request.
  • Type Conversion: The Spring framework automatically converts the string `"10"` to the integer `10`.
  • Spring Boot Configuration Properties: Sometimes, default values can be managed more efficiently using `@ConfigurationProperties` which allows for better separation of concerns and centralized configuration management.
  • Advanced Type Conversion: Spring framework's `ConversionService` can be customized if you need advanced type conversion logic beyond the default capabilities.

Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms