应用View Helper模式
下面的Helper可能对你在某些方面特别有用,但是最起码,他们要告诉你怎么在你的应用中使用View Helper模式。下面是一个定制标签的实现并且被声明在helpers.tld文件里。这个文件在web.xml 文件里做为一个条目和/helpers标签uri相关联。如下所示:
/helpers
/WEB-INF/tlds/helpers.tld
格式化文本
在下面的章节里,我将以一个用来格式化日期和货币的View Helper开始。虽然这个需求在Model里实现可能比较简单,但是你有很多原因使得你在View里实现它们,而不是在Model里。例如,你可能使用不同的格式来显示它们,或者可能内容因为要被不同的设置访问而必须提供不同的访问方式。
你可以在定制标签体内封装很多格式用来格式化标签所取得的数据,然后你给标签一个属性来取得使用者所需要的格式类型,根据这个属性选择相应的格式并将其输出出来。如下所示,你可以在标签库表述符里描述你的标签:
Listing 2. helpers.tld
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
web-jsptaglibrary_2_0.xsd"
version="2.0" >
1.0
2.0
helperTags
Tag library to support the examples in Chapter 8
FormatTag
jspbook.ch08.FormatTag
JSP
format
yes
true
这个标签的Model能够无所不包,在这个例子中,你将创建一个静态的JavaBeans包含两个String类型的属性,一个用来保存Date,一个用来保存货币。你将通过使用标准的JSP setProperty标签在页面里设置这些值。为了达到这样的目的,你的JavaBeans必须为这两个属性提供方法入门。如下所示,是用来产生JavaBeans的Java代码:
Listing 3. FormattingModel.java
package jspbook.ch08.beans;
import java.io.Serializable;
public class FormattingModel implements Serializable {
private String dateValue;
private String currencyValue;
public FormattingModel () {}
/* Accessor Methods */
public void setDateValue (String _date)
{
this.dateValue = _date;
}
public String getDateValue ()
{
return this.dateValue;
}
public void setCurrencyValue (String _currency)
{
this.currencyValue = _currency;
}
public String getCurrencyValue ()
{
return this.currencyValue;
}
}
标签是一个简单的body标签,由BodyTagSupport 类继承而来。所有的格式化代码都在formatValue()方法里。在doAfterBody()里,一旦获取了数据,这个方法就会被调用。调用formatValue()方法的结果被写回了页面标签所在的位置。你可以使用java.text包的类来格式化日期或货币,而且,你可以使用SimpleDateFormat 和 DecimalFormat类。
标签处理者也提供了Locale 对象,通过相应的set方法,能够完成对内容的国际化。因为这个标签的职责是格式化日期和货币,那么它必然在不同的地区有不同的格式化要求。看看下面的代码,特别是要注意formatValue()方法:
Listing 4. FormatTag.java
package jspbook.ch08;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.tagext.BodyContent;
import java.io.IOException;
import java.util.Locale;
import java.util.Calendar;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.NumberFormat;
import java.text.DecimalFormat;
public class FormatTag extends BodyTagSupport {
/* Locale object for internationalization of content */
private Locale locale;
/* Tag Attributes */
protected String format;
/* Static Constants */
private final static String DATE_LONG = "date";
private final static String NUMERIC_DECIMAL = "decimal";
private final static String NUMERIC_ROUNDED = "rounded";
private final static String NUMERIC_CURRENCY = "currency";
public FormatTag() {
locale = Locale.getDefault();
}
public void setLocale(Locale locale) {
this.locale = locale;
}
/* Process Tag Body */
public int doAfterBody() throws JspTagException {
try {
BodyContent body = getBodyContent();
JspWriter out = body.getEnclosingWriter();
/* Get Input Value */
String textValue = body.getString().trim();
/* Output Formatted Value */
out.println(formatValue(textValue));
}
catch (IOException e) {
throw new JspTagException(e.toString());
}
return SKIP_BODY;
}
/* Process End Tag */
public int doEndTag() throws JspTagException {
return EVAL_PAGE;
}
private String formatValue (String _input)
{
String formattedValue = "";
try {
if(format.equals(DATE_LONG)) {
Calendar cal = Calendar.getInstance();
cal.setTime(DateFormat.getDateInstance(
DateFormat.SHORT).parse(_input));
SimpleDateFormat df = new SimpleDateFormat("EEE, MMM d, yyyy");
formattedValue = df.format(cal.getTime());
} else if(format.equals(NUMERIC_DECIMAL)) {
DecimalFormat dcf = (DecimalFormat) NumberFormat.getInstance(locale);
dcf.setMinimumFractionDigits(2);
dcf.setMaximumFractionDigits(2);
formattedValue = dcf.format(dcf.parse(_input));
} else if(format.equals(NUMERIC_ROUNDED)) {
DecimalFormat dcf = (DecimalFormat) NumberFormat.getInstance(locale);
dcf.setMinimumFractionDigits(0);
dcf.setMaximumFractionDigits(0);
formattedValue = dcf.format(dcf.parse(_input));
} else if(format.equals(NUMERIC_CURRENCY)) {
float num = Float.parseFloat(_input);
DecimalFormat dcf = (DecimalFormat)
NumberFormat.getCurrencyInstance();
formattedValue = dcf.format(num);
}
}
catch (Exception e) {
System.out.println(e.toString());
}
return formattedValue;
}
/* Attribute Accessor Methods */
public String getFormat ()
{
return this.format;
}
public void setFormat (String _format)
{
this.format = _format;
}
}
最后,你将在JSP页面使用该标签,这里实在是没有什么新东西。页面声明一个JavaBeans来作为Model使用,在这个Model里设置值,使用不同的格式来显示这些值。这些格式化的动作通过FormatTag实现,该标签在helpers.tld里给定,并且在JSP页面使用taglib 指示符来声明。注意:你需要通过标签的一个属性来设置格式类型。format 属性就是用来指定一个格式类型的值,而这个值必须依赖于标签里设定的那些常量来确定。如下所示,是JSP代码:
Listing 5. formatHelper.jsp
Various Date and Currency Formats
| Format |
|---|
| Original Value |
|---|
| Formatted Value |
|---|
| Long Date |
| Decimal (NN.NN) |
| ${myBean.currencyValue} |
${myBean.currencyValue} |
| Integer (N,NNN) |
| ${myBean.currencyValue} |
${myBean.currencyValue} |
| Currency (N,NNN.NN) |
| ${myBean.currencyValue} |
${myBean.currencyValue} |
下图是显示结果:

本文介绍如何使用ViewHelper模式创建自定义标签,以实现日期和货币的格式化功能。通过一个具体的示例,展示了如何设计JavaBeans来存储数据,并利用自定义标签处理数据格式化。
3769

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



