freemarker写select组件
1、宏定义
<#macro select id datas value="" key="" text=""> <select id="${id}" name="${id}"> <option>---请选择---</option> <#list datas as data> <#if key!=""> <#if value == data[key]?string> <option value="${data[key]}" selected>${data[text]}</option> <#else> <option value="${data[key]}">${data[text]}</option> </#if> <#else> <#if value == data> <option value="${data}" selected>${data}</option> <#else> <option value="${data}">${data}</option> </#if> </#if> </#list> </select> </#macro>
2、封装类
/** * @Title:User.java * @Package:com.you.freemarker.model * @Description: * @author:Youhaidong(游海东) * @date:2014-6-26 下午10:28:01 * @version V1.0 */ package com.you.freemarker.model; /** * 类功能说明 * 类修改者 修改日期 * 修改说明 * <p>Title:User.java</p> * <p>Description:游海东个人开发</p> * <p>Copyright:Copyright(c)2013</p> * @author:游海东 * @date:2014-6-26 下午10:28:01 * @version V1.0 */ public class User { /** * 用户号 */ private int userNo; /** * 用户姓名 */ private String userName; /** * 用户年龄 */ private int userAge; /** * @return the userNo */ public int getUserNo() { return userNo; } /** * @param userNo the userNo to set */ public void setUserNo(int userNo) { this.userNo = userNo; } /** * @return the userName */ public String getUserName() { return userName; } /** * @param userName the userName to set */ public void setUserName(String userName) { this.userName = userName; } /** * @return the userAge */ public int getUserAge() { return userAge; } /** * @param userAge the userAge to set */ public void setUserAge(int userAge) { this.userAge = userAge; } /** * <p>Title:</p> * <p>Description:</p> * @param userNo * @param userName * @param userAge */ public User(int userNo, String userName, int userAge) { super(); this.userNo = userNo; this.userName = userName; this.userAge = userAge; } /** * <p>Title:</p> * <p>Description:</p> */ public User() { super(); } }
3、页面引入
<@items.select id="user" datas=users key="userNo" text="userName"/>
4、Junit测试方法
/** * * @Title:testSelect * @Description: * @param: * @return: void * @throws */ @Test public void testSelect() { List<User> users = Arrays.asList(new User(1,"张三丰",25), new User(2,"李思思",22), new User(3,"赵武",23), new User(4,"刘雪",20), new User(5,"朱顾",21), new User(6,"赵武",23), new User(7,"吴语",24), new User(8,"血玉",21)); root.put("users", users); studentPrint("address.ftl"); studentFile("address.ftl","address.html"); }
5、测试结果
(1)控制台打印
<select id="user" name="user"> <option>---请选择---</option> <option value="1">张三丰</option> <option value="2">李思思</option> <option value="3">赵武</option> <option value="4">刘雪</option> <option value="5">朱顾</option> <option value="6">赵武</option> <option value="7">吴语</option> <option value="8">血玉</option> </select>
(2)页面显示