自定义jsp标签

首先创建标签解析类:

import org.apache.taglibs.standard.lang.support.ExpressionEvaluatorManager;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

public class FormatTag extends TagSupport {
    private String type;
    private Object value;
    private String pattern;

    @Override
    public int doStartTag() throws JspException {
        if ("number".equals(type)){
            DecimalFormat decimalFormat=new DecimalFormat(pattern);
            decimalFormat.setRoundingMode(RoundingMode.DOWN);

            try {
                BigDecimal bigDecimal=new BigDecimal(value.toString());
                String result= decimalFormat.format(bigDecimal);
                pageContext.getOut().write(result);
            } catch (IOException e) {

            }
        }
        return 0;
    }


    public void setType(String type) {
        this.type = type;
    }

    public void setValue(String value) throws JspException {
        this.value = ExpressionEvaluatorManager.evaluate(
                "value", value.toString(), Object.class, this, pageContext);
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }
}

然后创建tld描述文件:

<?xml version="1.0" encoding="ISO-8859-1"?>

<taglib xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
        version="2.1">

    <tlib-version>1.0</tlib-version>
    <short-name>ft</short-name>
    <uri>http://udformat.com</uri>
    <tag>
        <name>format</name>
        <tag-class>com.cmst.utils.FormatTag</tag-class>
        <body-content>empty</body-content>
        <attribute>
            <name>type</name>
            <required>true</required>
        </attribute>
        <attribute>
            <name>value</name>
            <required>true</required>
            <rtexprvalue>true</rtexprvalue>
        </attribute>
        <attribute>
            <name>pattern</name>
        </attribute>
    </tag>
    <!-- Invoke 'Generate' action to add tags or functions -->

</taglib>

最后在jsp中引用即可:

<%@taglib prefix="ftn" uri="http://udformat.com" %>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值