Spring MVC
RequestParam
optional parameters
Java
web development

RequestParam in Spring MVC handling optional parameters

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In the development of web applications using Spring MVC, handling user inputs and HTTP requests efficiently is essential. One of the features offered by Spring MVC is the @RequestParam annotation, which provides a flexible way of handling HTTP request parameters. An essential aspect of using @RequestParam is managing optional parameters. This article delves into handling optional parameters in Spring MVC using @RequestParam, along with examples, technical explanations, and an overview in tabular form.

Understanding @RequestParam

@RequestParam is a Spring MVC annotation used to extract query parameters, form parameters, and path variables from HTTP requests. It binds request parameters to method parameters within a controller, simplifying data retrieval from client requests.

Basic syntax looks like this:

java
1@RequestMapping("/greeting")
2public String greeting(@RequestParam(name = "name", required = false, defaultValue = "World") String name) {
3    return "Hello, " + name;
4}

Handling Optional Parameters

By default, @RequestParam requires the parameter to be present in the request. However, you often need to handle optional parameters. This is achieved by setting the required attribute to false and optionally providing a defaultValue.

Syntax Explanation

  • required: A boolean value that specifies whether the parameter is mandatory. When set to false, the parameter is optional.
  • defaultValue: An optional attribute that allows specifying a default value when the parameter is not present in the request.

Example:

java
1@RequestMapping("/search")
2public String search(@RequestParam(name = "query", required = false, defaultValue = "default search") String query) {
3    return "Searching for: " + query;
4}

In this case, if the query parameter is missing from the request, "default search" will be used.

Practical Example with Multiple Parameters

Consider an application that filters products based on optional criteria such as category and price range.

java
1@RequestMapping("/filterProducts")
2public String filterProducts(
3    @RequestParam(name = "category", required = false) String category,
4    @RequestParam(name = "minPrice", required = false, defaultValue = "0") double minPrice,
5    @RequestParam(name = "maxPrice", required = false, defaultValue = "10000") double maxPrice) {
6
7    // Product filtering logic here
8    return "Filtering products in category: " + category
9           + ", with price range: " + minPrice + " to " + maxPrice;
10}

In this example:

  • category is optional, and if not provided, includes all categories.
  • minPrice defaults to 0 if not specified.
  • maxPrice defaults to 10000 if not specified.

Table: Key Points of @RequestParam Handling

Here's a concise summary of using @RequestParam for optional parameters.

AttributeTypeDescription
nameStringSpecifies the request parameter name to bind to.
requiredBoolDetermines if the parameter is mandatory. true: Parameter is required (default). false: Parameter is optional.
defaultValueStringProvides a default if the parameter is missing. If required = false and no defaultValue, defaults to null.

JSON and Complex Objects with @RequestParam

While @RequestParam is typically used for simple data types, Spring MVC allows for more complex types using JSON. This is particularly useful for web services.

Consider a scenario where you handle JSON input in your API:

java
1@RequestMapping("/updateSettings")
2public String updateSettings(@RequestParam(name = "settings", required = false) String settingsJson) {
3    ObjectMapper objectMapper = new ObjectMapper();
4    MySettings settings = objectMapper.readValue(settingsJson, MySettings.class);
5
6    // Process settings
7    return "Settings updated";
8}

When handling JSON, ensure the client sends a well-formed JSON string, and configure Spring's message converters appropriately.

Conclusion

The @RequestParam annotation is a powerful tool in Spring MVC applications, providing a seamless way to handle HTTP request parameters, whether optional or mandatory. By understanding its attributes and usage, developers can craft flexible and robust request mappings, effectively managing both simple and complex data with minimal boilerplate code. Ultimately, leveraging optional parameters enhances application resilience and improves the user experience through intuitive defaults and graceful handling of incomplete inputs.


Related reading
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
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.