SpringBoot thymeleaf页面下拉框使用枚举类

1. 定义枚举类,用来封装下拉框数据

package com.example.jmw.common.enums;

public enum CsvMasterTypes {

    受注ファイル("1", "受注ファイル"),
    受注先マスタ("2", "受注先マスタ");
    
    private String code;
    
    private String name;

    CsvMasterTypes(String code, String name) {
        this.code = code;
        this.name = name;
    }

    public String getCode() {
        return code;
    }
    
    public String getName() {
        return name;
    }
}

2.创建一个form,用来封装返回到前台的数据

import com.example.jmw.common.enums.CsvMasterTypes;
import lombok.Data;

@Data
public class Test12Form {
    
    // 自定义枚举Array类型
    private CsvMasterTypes[] csvMasterTypes;
}

3. Controller层直接将数据放到ModelAndView中返回给前台

@Controller
@RequestMapping("/test12")
public class Test12Controller {

    // 页面初期表示
    @RequestMapping("/init")
    public ModelAndView init() {
    	
        Test12Form test12Form = new Test12Form();
        // 将自定义枚举类放入form对象中
        test12Form.setCsvMasterTypes(CsvMasterTypes.values());
        
        // 指定页面名称和要返回到页面中的数据
        ModelAndView modelView = new ModelAndView();
        modelAndView.setViewName("test12");
        modelAndView.addObject("entity", test12Form);
        
        return  modelAndView;
    }
}

4. 前台遍历获取

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <title>展示后台的枚举类数据</title>
</head>
<body>
    <label>
        <select th:object="${entity}">
        	<!--
        		csvMasterTypes相当于后台form中的CsvMasterTypes[]
        		enum相当于我们自定义的枚举类
			-->
            <th:block th:each="enum : *{csvMasterTypes}">
                <option th:value="${enum.code}">[[${enum.name}]]</option>
            </th:block>
        </select>
    </label>
</body>
</html>

5. 效果

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值