freemarker迭代list、map等常規操作
阿新 • • 發佈:2018-11-05
轉自:https://blog.csdn.net/wickedvalley/article/details/65937189
一、controller開始準備模型、資料
1.po類
1 package com.hbut.ssm.po; 2 3 /** 4 * pojo類 5 * 6 */ 7 public class Children { 8 9 private String name; 10 private Integer age; 11 privateString gender; 12 13 public Children(String name, Integer age, String gender) { 14 super(); 15 this.name = name; 16 this.age = age; 17 this.gender = gender; 18 } 19 public String getName() { 20 returnname; 21 } 22 public void setName(String name) { 23 this.name = name; 24 } 25 public Integer getAge() { 26 return age; 27 } 28 public void setAge(Integer age) { 29 this.age = age; 30 } 31 publicString getGender() { 32 return gender; 33 } 34 public void setGender(String gender) { 35 this.gender = gender; 36 } 37 38 }
2.模型資料準備
1 @RequestMapping("/freemarker") 2 public String index(Model model,HttpServletRequest request){ 3 //1.迭代list 4 List<Children> childrenList= new ArrayList<Children>(); 5 childrenList.add(new Children("張三", 25, "男")); 6 childrenList.add(new Children("李四", 28, "男")); 7 childrenList.add(new Children("小紅", 22, "女")); 8 9 10 //2.迭代map 11 Map<String,Object> userMap = new HashMap<String,Object>(); 12 userMap.put("address","wuhan"); 13 userMap.put("birthday","11月01"); 14 userMap.put("phone",null); 15 16 //3.迭代常規物件 17 model.addAttribute("flag",1); 18 model.addAttribute("home","wuhan"); 19 20 //list、map新增進model 21 model.addAttribute("childrenList",childrenList); 22 model.addAttribute("userMap",userMap); 23 return "free"; 24 }
說明:資料有常規String、list、map的資料,需要freemarker頁面解析資料
二、freemarker常用解析指令
1 <Html> 2 <head> 3 <title>lerning---freemarker</title> 4 </head> 5 <body> 6 1.list iterator 7 <table border="1" cellspacing="0" cellpadding="20"> 8 <!--1. list--> 9 <#list childrenList as chilren> 10 <tr> 11 <td>${chilren.name}</td><td>${chilren.age}</td><td>${chilren.gender}</td> 12 </tr> 13 </#list> 14 </table> <br> 15 16 2.if jugde <br> 17 <!--2.測試if--> 18 <#if flag==1> 19 result:flag==1 20 </#if><br><br> 21 22 3.converter lowercase to uppercase<br> 23 <!--3. ?代替為. 後面接內建函式,將字串轉為大寫--> 24 result:${home?upper_case}<br><br> 25 26 4.map iterator <br> 27 <!--4.迭代map中的key/value對--> 28 <#list userMap?keys as key> 29 ${key}--${userMap[key]!("default value")}<br> 30 </#list> 31 32 <body> 33 </html>
三、freemarker顯示結果