Spring
RequestParam
Enum
Java
Spring MVC

Spring's RequestParam with Enum

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

In Spring MVC, handling request parameters is a common task, especially when building RESTful web services or web applications. The @RequestParam annotation is a powerful tool in Spring's arsenal that allows easy access to query parameters of HTTP requests. Combining this with Java Enums can simplify the handling of predefined values and make your code more readable and maintainable. This article will delve into using @RequestParam with Enums effectively.

@RequestParam Basics

The @RequestParam annotation is used to bind HTTP request parameters to method parameters in a controller class.

java
1@GetMapping("/greet")
2public String greetUser(@RequestParam(name = "name", defaultValue = "Guest") String name) {
3    return "Hello, " + name;
4}

In this snippet, the @RequestParam maps the query parameter name to the method parameter name. If the request parameter is not provided, the default value "Guest" is used.

Using Enums with @RequestParam

Enum Basics

Enums are a special Java type used to define collections of constants. They offer type safety and can make code more readable compared to using fixed strings or integers.

java
public enum Color {
    RED, GREEN, BLUE
}

Binding Enums with @RequestParam

Enums integrate seamlessly with @RequestParam, ensuring that only valid, predefined values are passed as request parameters.

java
1@GetMapping("/color")
2public String selectColor(@RequestParam Color color) {
3    return "Selected color: " + color;
4}

Handling Invalid Enums

By default, if an invalid enum value is passed, Spring throws a 400 Bad Request error. To provide a more user-friendly error message, you can leverage @ExceptionHandler in your controller.

java
1@ControllerAdvice
2public class GlobalExceptionHandler {
3    
4    @ExceptionHandler(IllegalArgumentException.class)
5    @ResponseBody
6    public ResponseEntity<String> handleInvalidEnumValue(IllegalArgumentException ex) {
7        return new ResponseEntity<>("Invalid color specified. Please use RED, GREEN, or BLUE.", HttpStatus.BAD_REQUEST);
8    }
9}

Advanced Enum Mapping

Sometimes, request parameter values may not directly match enum names. In such cases, a custom mapping strategy can be implemented.

Enum with Additional Attributes

Extend the enum to include properties and a static method to perform custom mapping:

java
1public enum Color {
2    RED("r"),
3    GREEN("g"),
4    BLUE("b");
5    
6    private String code;
7    
8    Color(String code) {
9        this.code = code;
10    }
11    
12    public static Color fromCode(String code) {
13        for (Color color : values()) {
14            if (color.code.equals(code)) {
15                return color;
16            }
17        }
18        throw new IllegalArgumentException("Invalid color code: " + code);
19    }
20}

Using Custom Mapping

Utilize the custom mapping in a controller method:

java
1@GetMapping("/colorByCode")
2public String selectColorByCode(@RequestParam String code) {
3    Color color = Color.fromCode(code);
4    return "Selected color: " + color;
5}

Summary Table

Feature/FunctionalityDescription
@RequestParam UsageBinds HTTP request parameters to method parameters in Spring MVC controllers.
Enum BenefitsProvides type safety and improves code readability.
Integration with EnumsDirect support for Enums as request parameters, with automatic parsing and validation.
Error HandlingThrows 400 Bad Request for invalid enums; custom error messages can be implemented using @ExceptionHandler.
Custom Enum MappingAllows mapping request parameter values to enums using additional attributes and custom logic.

Additional Considerations

  • Performance: Enums are memory-efficient and can improve application performance due to their compile-time constants.
  • Documentation: When using Enums, it is beneficial to document the accepted values for better API usability.
  • Default Values: Enums can also be used with default values similar to other data types in @RequestParam.

Example with Default Enum

java
1@GetMapping("/defaultColor")
2public String selectDefaultColor(@RequestParam(defaultValue = "RED") Color color) {
3    return "Selected color: " + color;
4}

Conclusion

Leveraging Spring's @RequestParam with Enums can greatly enhance your application's robustness and readability. Enums provide a structured way to handle data, ensuring that only valid, predefined values are processed. By combining these with custom error handling and mapping strategies, your application's response to user inputs can be both precise and informative.


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.