在 Spring MVC 中使用枚举作为请求参数

枚举是Java中的一种特殊数据类型,用于表示一组固定的常量。控制器方法可以采用枚举作为参数,Spring MVC会自动翻译将传入请求参数的值设置为适当的枚举常量。

枚举数据类型的示例:

enum CoffeeSize {
    SMALL, MEDIUM, LARGE
}

在 Spring MVC 应用程序中使用枚举作为请求参数的好处

  • 在控制器类中使用枚举作为方法参数可提供类型安全性。
  • 枚举允许集中验证可能的值。
  • 默认情况下,枚举名称用于匹配参数名称。
  • 枚举用于根据以枚举表示的预定义条件进行过滤/搜索。

Spring MVC 中枚举的用例
  • 请求映射:根据枚举路径将 URL 映射到控制器方法/
  • 默认值:如果缺少参数,则返回默认枚举以避免 null 检查。
  • 国际化:将枚举名称/标签外部化到属性文件以进行本地化。
  • 错误处理:根据枚举参数值自定义错误消息。
  • 缓存:使用枚举作为缓存键,而不是硬编码字符串。

将枚举实现为请求参数
  1. 定义枚举
  2. 控制器方式
  3. 请求映射
  4. 处理无效值

创建一个Enum类[CourseType]

package com.demo.model;
public enum CourseType { JAVA, SPRING, DSA, PYTHON }

创建控制器【CourseController】

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"
    } 
}

创建视图

  • 该文件位于 src/main/resources/templates/courses.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>

运行应用程序

  • 您可以从 IDE 或使用 Spring Boot 提供的命令行工具运行 Spring Boot 应用程序。

mvn spring-boot:run

在浏览器中访问 http://localhost:8080/courses,您就会看到课程页面。

结论
在本文中,我们了解到,只要有一组固定的可能值,使用枚举作为请求参数比使用字符串更受欢迎。与普通字符串相比,枚举提供了类型安全、意图明确、避免错误并使代码整体更加健壮。