JSP 遍历迭代 Enum 枚举

时间:2022-02-24 19:38:51

JSP 遍历迭代 Enum 枚举

现有枚举定义

package com.king.enity.enm;

public enum EnumGoldFlowType {

recharge("充值"), withdraw("提现"), exchange("兑换商品"), subexchange("代理兑换商品");

private EnumGoldFlowType(String _desc) {
this.desc = _desc;
}

private final String desc;

public String getDesc() {
return this.desc;
}
}

方式一:在JSP中直接遍历枚举

<c:set var="flowTypes" value="<%= com.king.enity.enm.EnumGoldFlowType.values() %>"/>
<c:forEach var="type" items="${flowTypes}">
<option value="${type.name()}" >${type.getDesc()}</option>
</c:forEach>

方式二:ModelAndView传递枚举数组到JSP中遍历

@RequestMapping("listflow.shtml")
public ModelAndView listflow(HttpServletRequest request){
ModelAndView mav = new ModelAndView("zan/usergold/usergoldflow_list");
mav.addObject("typeList", EnumGoldFlowType.values());
return mav;
}

<c:forEach items="${typeList }" var="item">
<option value="${item.name()}" >${item.getDesc()}</option>
</c:forEach>

方式三:用Map装载枚举,然后在JSP中遍历Map

@RequestMapping("listflow.shtml")
public ModelAndView listflow(HttpServletRequest request){
ModelAndView mav = new ModelAndView("zan/usergold/usergoldflow_list");
Map<String, String> typeMap = new HashMap<>();
for (EnumGoldFlowType type : EnumGoldFlowType.values()) {
typeMap.put(type.name(), type.getDesc());
}
mav.addObject("typeMap", typeMap);
return mav;
}

<c:forEach items="${typeMap }" var="item">
<option value="${item.key}" >${item.value}</option>
</c:forEach>

参考

http://*.com/questions/1835683/how-to-loop-through-a-hashmap-in-jsp