Using Enums as Request Parameters in Spring MVC Last Updated : 28 Apr, 2025 Comments Improve Suggest changes Like Article Like Report Enums are a special data type in Java used for representing a fixed set of constants. Controller methods can take enums as parameters, Spring MVC will automatically translate the value of the incoming request parameter to the appropriate enum constant. Example of Enum Data Type: enum CoffeeSize { SMALL, MEDIUM, LARGE}Benefits of Using Enums as Request Parameters in Spring MVC ApplicationsUsing enums as method parameters in controller classes provides type safety.Enums allow centralized validation of possible values.The enum name is used to match the parameter name by default.Enums are used for filtering/searching on predefined criteria expressed as enums.Use cases of Enums in Spring MVCRequest Mapping: Map URLs to controller methods based on enum paths/Default Values: Return a default enum if the parameter is missing to avoid null checks.Internationalization: Externalize enum names/labels to properties files for localization.Error Handling: Customize error messages based on enum parameter values.Caching: Use enums as cache keys instead of hardcoded strings.Implementing Enums as Request ParametersDefine the enumController methodRequest mappingHandle Invalid ValuesSteps of Enum ImplementationStep 1: Set up a new Spring MVC projectCreate a new Maven project in your preferred IDE (e.g., IntelliJ or Eclipse or Spring Tool Suite) and add the following dependencies.Project Structure:Step 2: Create an Enum class [CourseType]package com.demo.model;public enum CourseType { JAVA, SPRING, DSA, PYTHON }Step 3: Create a Controller [CourseController] Java package com.demo.controller; import com.demo.model.CourseType; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class CourseController { @GetMapping("/courses") public String getCourses(@RequestParam(name = "courseType", defaultValue = "JAVA") CourseType courseType, Model model) { model.addAttribute("selectedCourseType", courseType); model.addAttribute("allCourseTypes", CourseType.values()); return "courses"; } } Step 4: Create View This file, located in src/main/resources/templates/courses.html HTML <!-- src/main/resources/templates/courses.html --> <!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Courses</title> <style> body { font-family: 'Arial', sans-serif; margin: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; height: 100vh; background-color: #f4f4f4; } h2 { color: #333; } form { margin-bottom: 20px; } label { font-weight: bold; } select { padding: 5px; font-size: 16px; } h3 { color: green; } </style> </head> <body> <h2>Our Available Courses </h2> <form action="/courses" method="get"> <label for="courseType">Select a course :</label> <select name="courseType" id="courseType" onchange="this.form.submit()"> <option th:each="type : ${allCourseTypes}" th:value="${type}" th:text="${type}" th:selected="${type == selectedCourseType}"></option> </select> </form> <h3>Selected Course : <span th:text="${selectedCourseType}"></span></h3> </body> </html> Step 5: Run the ApplicationYou can run your Spring Boot application from your IDE or by using the command-line tool provided by Spring Boot.mvn spring-boot:runVisit http://localhost:8080/courses in your browser, and you should see the courses page.Output of the Project:ConclusionIn this article, we have learned that, using enums is preferred over strings as request parameters whenever there is a fixed set of possible values. They provide type safety, clarity of intent, avoid errors and make the code more robust overall compared to plain strings. Comment More infoAdvertise with us Next Article Using Enums as Request Parameters in Spring MVC P pranay0911 Follow Improve Article Tags : Java Geeks Premier League Advance Java Java-Spring Java-Spring-MVC Geeks Premier League 2023 +2 More Practice Tags : Java Similar Reads Query String and Query Parameter in Spring MVC According to Wikipedia "A query string is a part of a uniform resource locator (URL) that assigns values to specified parameters. A query string commonly includes fields added to a base URL by a Web browser or other client application, for example as part of an HTML, choosing the appearance of a pag 6 min read JSON Parameters with Spring MVC JSON (JavaScript Object Notation) is a lightweight data exchange format. We can interchange data from one application to another from client to server. We have many data interchange formats available in the market. Like properties files, XML files, YAML files, JSON files, etc. But when compared to o 14 min read Spring MVC - Get Exchange Rate Values using REST API People are doing business, and developing software for geographical locations. That means the calculation of a software price will vary globally. During those scenarios, we need to know about the exchange rates for a given currency. Nowadays many open source REST API calls are available and among th 5 min read Spring MVC Optional @PathVariable in Request URI Spring MVC becomes even more easy with the use of the @PathVariable annotation and by the use of Optional classes within the Request URI to make robust Spring Applications. In this article, we will look into the necessity of the two components, delving into their prerequisites and understanding why 3 min read Request Body and Parameter Validation with Spring Boot For the Spring-Based RESTful Application, it is important to handle the incoming API requests and meet the expected format criteria. To handle this situation, we used @RequestBody, @RequestParam, and @Valid Annotation in the Spring Boot Application to validate the required format of the incoming req 4 min read Spring - Add New Query Parameters in GET Call Through Configurations When a client wants to adopt the API sometimes the existing query parameters may not be sufficient to get the resources from the data store. New clients can't onboard until the API providers add support for new query parameter changes to the production environment. To address this problem below is a 4 min read How to Make get() Method Request in Java Spring? Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc 3 min read Returning Errors Using ProblemDetail in Spring Boot In a Spring Boot application, error handling is an important aspect of providing a robust and user-friendly API. Traditionally, Spring Boot has provided various methods like @ExceptionHandler, ResponseEntityExceptionHandler, and @ControllerAdvice for handling exceptions. With Spring Framework 6 and 7 min read Spring MVC - Basic Example using JSTL JSP Standard Tag Library (JSTL) is a set of tags that can be used for implementing some common operations such as looping, conditional formatting, and others. JSTL aims to provide an easy way to maintain SP pages The use of tags defined in JSTL has Simplified the task of the designers to create Web 8 min read How to Make Put Request in Spring Boot? Java language is one of the most popular languages among all programming languages. There are several advantages of using the Java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every conc 3 min read Like