一個簡單的后台商品展示列表demo:
在使用模板引擎時,對於“類目”條件判斷的字段,通常情況是寫死在頁面的:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>商品管理</title> <link href="https://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div id="wrapper" class="toggled"> <#--主要內容 --> <div id="page-content-wrapper"> <div class="container-fluid"> <div class="row clearfix"> <div class="col-md-12 column"> <table class="table table-bordered table-hover"> <thead> <tr> <th>商品id</th> <th>名稱</th> <th>類目</th> <th>價格</th> </tr> </thead> <tbody> <#list productPage.content as product> <tr> <td>${product.productId}</td> <td>${product.productName}</td> <td> <#if product.productType == 0> 女生最愛 <#elseif product.productType == 1> 男生最愛 <#elseif product.productType == 2> 小孩最愛 </#if> </td> <td>${product.productPrice}</td> </tr> </#list> </tbody> </table> </div> </div> </div> </div> </div> <script src="https://cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> </body> </html>
但使用到“類目”的頁面一旦多起來,這種方式修改起來太不靈活了,所以,可以寫一個枚舉工具類,讓代碼更靈活,先寫一個枚舉接口:
public interface CodeEnum { Integer getCode(); }
枚舉類工具:
public class EnumUtil { public static <T extends CodeEnum>T getByCode(Integer code, Class<T> enumClass){ // 遍歷枚舉類的值,返回與code匹配的實例 for (T each : enumClass.getEnumConstants()) { if (each.getCode().equals(code)) { return each; } } return null; } }
枚舉類:
public enum ProductTypeEnum implements CodeEnum { GIRLS_LOVE(0, "女生最愛"), BOYS_LOVE(1, "男生最愛"), KIDS_LOVE(2, "小孩最愛") ; private Integer code; private String message; @Override public Integer getCode() { return code; } public String getMessage() { return message; } ProductTypeEnum(Integer code, String message) { this.code = code; this.message = message; } }
在實體類中,添加獲得枚舉實例的方法:
@Entity @DynamicUpdate @Data public class Product { // 商品id @Id private String productId; /*商品名稱*/ private String productName; /*類目編號*/ private Integer productType; /*單價*/ private BigDecimal productPrice; /*獲取商品類目*/ @JsonIgnore public ProductTypeEnum getProductTypeEnum() { return EnumUtil.getByCode(productType, ProductTypeEnum.class); } }
然后,將模板頁面改成:
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <title>商品管理</title> <link href="https://cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"> </head> <body> <div id="wrapper" class="toggled"> <#--主要內容 --> <div id="page-content-wrapper"> <div class="container-fluid"> <div class="row clearfix"> <div class="col-md-12 column"> <table class="table table-bordered table-hover"> <thead> <tr> <th>商品id</th> <th>名稱</th> <th>類目</th> <th>價格</th> </tr> </thead> <tbody> <#list productPage.content as product> <tr> <td>${product.productId}</td> <td>${product.productName}</td>
<td>${product.getProductTypeEnum().message}</td>
<td>${product.productPrice}</td> </tr> </#list> </tbody> </table> </div> </div> </div> </div> </div> <script src="https://cdn.bootcss.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> </body> </html>
這樣,代碼改動更加靈活了。