首先创建标签解析类:
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" %>
409

被折叠的 条评论
为什么被折叠?



