• Freemarker 自定义标签 实现TemplateDirectiveModel


    1 自定义标签需要实现TemplateDirectiveModel这个接口中的execute方法 实例代码如下

    public class UserListDirective implements TemplateDirectiveModel{
    
        @Autowired
        private UserDAO  userDao;
        @Override
        public void execute(Environment env, Map params, TemplateModel[] loopVars,
                TemplateDirectiveBody body)
                          throws TemplateException, IOException {
            String name = params.get("name").toString();
            List<User> userlist = userDao.findByProperty("name", name);
    
            env.setVariable("userList", getBeansWrapper().wrap(userlist));
            body.render(env.getOut());
        }
    
        public static BeansWrapper getBeansWrapper(){
            BeansWrapper beansWrapper =
                             new BeansWrapperBuilder(Configuration.VERSION_2_3_21).build();
            return beansWrapper;
        }
    }
    

    2 配置 UserListDirective 到spring bean xml中

    <bean id="userListDirective" class="com.action.directive.UserListDirective"></bean>
    

    3 将spring bean 设置到freemarkerConfig全局变量中去。

    <bean id="freemarkerConfig2"
            class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
            <property name="templateLoaderPath" value="/" />
            <property name="freemarkerVariables">
                <map >
                    <entry key="userListDirective" value="userListTag" />
                </map>
            </property>
            <property name="freemarkerSettings">
                <props>
                    <prop key="template_update_delay">0</prop>
                    <prop key="defaultEncoding">UTF-8</prop>
                    <prop key="url_escaping_charset">UTF-8</prop>
                    <prop key="locale">zh_CN</prop>
                    <prop key="boolean_format">true,false</prop>
                    <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                    <prop key="date_format">yyyy-MM-dd</prop>
                    <prop key="time_format">HH:mm:ss</prop>
                    <prop key="number_format">0.######</prop>
                    <prop key="whitespace_stripping">true</prop>
                </props>
            </property>
        </bean>
    

    4 ftl文件中的访问方式

    <@userListTag name="zhangsan">
        <#if userList?? && userList?size gt 0>
            <#list userList as user>
                <a href="">${user.name}</a>
            </#list>
        </#if>
    </@userListTag>
  • 相关阅读:
    spring(2)
    Android之滑动按钮实现Demo
    spring(1)
    spring(4)
    Android之ImageSwitch控件
    使用非阻塞ServerSocketChannel、SocketChannel代替ServerSocket和Socket
    Android之界面刷新(invalidate和postInvalidate使用)
    Android之改变控件的背景及形态
    Android之获得内存剩余大小与总大小
    OpenCV中矩阵的归一化
  • 原文地址:https://www.cnblogs.com/dixinyunpan/p/5786995.html
Copyright © 2020-2023  润新知