【发布时间】:2016-04-04 06:01:51
【问题描述】:
我目前正在进行 struts 升级(从 struts 1.x 迁移到 2.x)
我的项目有一个自定义标签处理程序类,用于在应用程序中格式化数字
TLD 文件
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>f</shortname>
<uri>http://jakarta.apache.org/struts/tags-html</uri>
<tag>
<name>formatNumber</name>
<tagclass>com.taghandler.FormatNumberTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>name</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>property</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>scope</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
<attribute>
<name>format</name>
<required>false</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
</taglib>
FormatNumberTag 类
public class FormatNumberTag extends TagSupport
{
protected String name = null;
protected String property = null;
protected String scope = null;
protected String format = null;
//getters and setters of above member variables
public int doStartTag() throws JspException
{
// Look up the requested bean (if necessary)
Object bean = null;
if (RequestUtils.lookup(pageContext, name, scope) == null)
{
return (SKIP_BODY); // Nothing to output
}
// Look up the requested property value
Object value = RequestUtils.lookup(pageContext, name, property, scope);
if (value == null)
{
return (SKIP_BODY); // Nothing to output
}
String output = null;
if (format.equalsIgnoreCase(MyConstants.PRICE_FORMAT))
{
output = CustomConverter.priceFormat(value); //custom class which formats number
}
else if (format.equalsIgnoreCase(MyConstants.PERCENTAGE_FORMAT))
{
output = CustomConverter.positionFormat(value); //custom class which formats number
}
ResponseUtils.write(pageContext, output);
// Continue processing this page
return (SKIP_BODY);
}
}
JSP
<f:formatNumber name="AccountBean" property="floatingRate" format="percentage" />
这里,AccountBean 是 bean,floatingRate 是属性,百分比是格式。
1) 在上面的标签处理程序类中, (org.apache.struts.util.RequestUtils)RequestUtils.lookup & (org.apache.struts.util.ResponseUtils)ResponseUtils.write 方法 使用的是 struts1 库的一部分。
- struts 2 中对应的方法和类有哪些?
2) 在 JSP 中,在自定义标签中传递了 3 个值/属性(accountBean、floatingRate、percentage)。
如何在struts 2中将属性传递给自定义标签?
如何将 bean、属性和格式传递给 struts 2 中的自定义标签? 请举个例子
【问题讨论】:
-
自定义标签是自定义标签;使用您在任何其他非 Struts 自定义标签中使用的方法。也就是说,你为什么要这样做?是不是已经有自定义标签可以进行这样的格式化?
-
我在自定义标签处理程序类中使用带有格式化逻辑的自定义标签来格式化数字。我可以知道您在谈论哪个自定义标签进行格式化吗?
-
我使用了 s:text 标签来格式化数字。它工作正常,但我找不到用于在括号中格式化负数的消息格式。您能否提供用于在括号中格式化负数的消息格式,即示例:-0.52 应显示为 (0.52)
-
IIRC Java 数字格式通过用分号分隔格式字符串来支持“负数”格式,例如 chortle.ccsu.edu/java5/Notes/chap24B%5Cch24B_15.html 我会从那里开始,看看这是否有效。
-
感谢您的链接。我找到了解决方案。我使用消息格式 - {0,number,##0.00'%';(##0.00)'%'} 来格式化负值。
标签: java jsp struts2 custom-tags