Springboot + Freemarker项目中使用自定义注解
2018-03-08 15:04
651 查看
最近在做的项目中使用到了springboot + freemarker的技术,同时项目里多个controller中都需要查询一个公有的数据集合,一般做法是直接在每个controller的方法中通过model.addAttribute(“xx”, xx);的方式手动设置,但这样就有个明显的问题就是:重复代码!这是不能忍受的。考虑到jsp中的可以使用自定义标签,因此今天尝试了一下在freemarker中使用自定义标签。
因为这三个列表基本都是同页面显示,因此,就放到一个类中,通过method区分调用。
使用方法跟自定义宏(macro)用法一样,直接使用
注:ftl中通过@调用自定义标签时,后面可以跟任意参数(由此可以根据具体业务自定义标签)
Springboot + Freemarker项目中使用自定义注解
1.创建类并实现TemplateDirectiveModel
@Component public class CustomTagDirective implements TemplateDirectiveModel { @Autowired private RepBankBranchService bankBranchService; @Override public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException { DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_25); environment.setVariable("listParentBanks", builder.build().wrap(bankBranchService.listParents())); templateDirectiveBody.render(environment.getOut()); } }
因为这三个列表基本都是同页面显示,因此,就放到一个类中,通过method区分调用。
2.创建Freemarker配置类
@Configuration public class FreeMarkerConfig { @Autowired protected freemarker.template.Configuration configuration; @Autowired protected CustomTagDirective customTagDirective; @PostConstruct public void setSharedVariable() { // icbcTag即为页面上调用的标签名 configuration.setSharedVariable("icbcTag", customTagDirective); } }
3.ftl中使用自定义的标签
<@icbcTag method="listParentBanks"> <#if listParentBanks?? && listParentBanks?size gt 0> <#list listParentBanks as item> <option value="${item.id}">${item.name}</option> </#list> </#if> </@icbcTag>
使用方法跟自定义宏(macro)用法一样,直接使用
<@标签名>${值}</@标签名>即可。
注:ftl中通过@调用自定义标签时,后面可以跟任意参数(由此可以根据具体业务自定义标签)
Springboot + Freemarker项目中使用自定义注解
相关文章推荐
- Spring Boot项目中自定义注解的使用
- Spring Boot项目中自定义注解的使用
- springboot 项目使用freemarker 配置之后,访问静态和动态页面的方法
- J2EE项目使用自定义注解实现基于SpringMVC + Mybatis + Mysql的读写分离
- SpringBoot使用自定义注解+拦截器 实现日志记录
- 详解使用Spring Boot的AOP处理自定义注解
- 使用Spring Boot的AOP处理自定义注解
- SpringBoot系列三:SpringBoot基本概念(统一父 pom 管理、SpringBoot 代码测试、启动注解分析、配置访问路径、使用内置对象、项目打包发布)
- 【HAVENT原创】使用 Spring Boot 的 AOP 自定义注解
- SpringBoot使用自定义注解实现权限拦截的示例
- springboot项目 打成war包 使用自定义tomcat配置
- 从零学spring boot--集成mybatis--项目--使用注解方式
- SpringBoot实践之(十五)---自定义注解Annotation的使用
- SpringBoot+Freemarker 项目ftl中使用include的异常
- 使用SpringBoot通过自定义注解+AOP+全局异常处理实现参数统一非空校验
- (25)Spring Boot使用自定义的properties【从零开始学Spring Boot】
- 深入Spring:自定义注解加载和使用
- Spring Boot使用自定义的properties
- 项目中使用spring配置文件好,还是注解好?
- (32)Spring Boot使用@SpringBootApplication注解,从零开始学Spring Boot