自定义标准标签之c标签(1)

自定义标准标签之c标签(1)

1.如何定义一个新的标签

要使用一个标签库首先要写一个小东西,这里我们拿我们常用的c标签举例:

<%@ taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core” %>

我们需要写一个.tld文件内容如下
在这里插入图片描述
如果还是不是很清楚的话就看下面的吧!

在这里插入图片描述

!哦,对了我们还需要写一个助手类。那么我们的zking的标签就定义好了

在这里插入图片描述

package com.zking.jsp;

import javax.servlet.jsp.JspException;
import javax.servl
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 中使用 Freemarker 模板引擎时,可以通过自定义标签来实现一些常用的功能。下面介绍如何自定义一个列表标签。 首先,创建一个类,实现 `freemarker.template.TemplateDirectiveModel` 接口。这个接口只有一个方法 `execute`,需要在其中实现自定义标签的逻辑。例如: ``` import java.io.IOException; import java.util.Map; import freemarker.core.Environment; import freemarker.template.TemplateDirectiveBody; import freemarker.template.TemplateDirectiveModel; import freemarker.template.TemplateException; import freemarker.template.TemplateModel; import freemarker.template.TemplateModelException; public class CustomListDirective implements TemplateDirectiveModel { @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { // 获取参数 String items = params.get("items").toString(); String separator = params.get("separator").toString(); // 分割字符串,生成列表 String[] itemList = items.split(","); StringBuilder result = new StringBuilder(); for (String item : itemList) { result.append(item).append(separator); } // 输出结果 env.getOut().write(result.toString()); } } ``` 这个类实现了一个简单的列表标签,根据传入的参数 `items` 和 `separator`,将 `items` 字符串按照 `separator` 分割生成列表,并输出。 接着,在 Spring Boot 的配置类中注册这个自定义标签: ``` import java.util.HashMap; import java.util.Map; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import freemarker.template.Configuration; import freemarker.template.TemplateDirectiveModel; @Configuration public class FreemarkerConfig { @Bean public Configuration freemarkerConfig() { Configuration configuration = new Configuration(Configuration.VERSION_2_3_28); configuration.setClassForTemplateLoading(this.getClass(), "/templates"); // 注册自定义标签 Map<String, TemplateDirectiveModel> directives = new HashMap<>(); directives.put("customList", new CustomListDirective()); configuration.setSharedVariable("directives", directives); return configuration; } } ``` 这里将自定义标签注册到了 `Configuration` 中,然后在模板中使用 `<@directives.customList items="a,b,c" separator="-" />` 的方式调用即可。 需要注意的是,在模板中使用自定义标签时需要加上 `@` 符号,例如 `<@directives.customList ... />`。另外,`directives` 名称可以自定义,只要与 `freemarkerConfig` 中设置的名称一致即可。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值