您的位置:首页 > Web前端 > JavaScript

JSP设计模式基础:View Helper模式——学习如何使用View Helper模式使得Model数据适应表现层的需要(2)

2006-02-24 22:56 1131 查看
应用View Helper模式
下面的Helper可能对你在某些方面特别有用,但是最起码,他们要告诉你怎么在你的应用中使用View Helper模式。下面是一个定制标签的实现并且被声明在helpers.tld文件里。这个文件在web.xml 文件里做为一个条目和/helpers标签uri相关联。如下所示:
<taglib>
<taglib-uri>/helpers</taglib-uri>
<taglib-location>/WEB-INF/tlds/helpers.tld</taglib-location>
</taglib>

格式化文本
在下面的章节里,我将以一个用来格式化日期和货币的View Helper开始。虽然这个需求在Model里实现可能比较简单,但是你有很多原因使得你在View里实现它们,而不是在Model里。例如,你可能使用不同的格式来显示它们,或者可能内容因为要被不同的设置访问而必须提供不同的访问方式。
你可以在定制标签体内封装很多格式用来格式化标签所取得的数据,然后你给标签一个属性来取得使用者所需要的格式类型,根据这个属性选择相应的格式并将其输出出来。如下所示,你可以在标签库表述符里描述你的标签:
Listing 2. helpers.tld

<?xml version="1.0" encoding="ISO-8859-1" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
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" >
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>helperTags</short-name>
<description>
Tag library to support the examples in Chapter 8
</description>

<tag>
<name>FormatTag</name>
<tag-class>jspbook.ch08.FormatTag</tag-class>
<body-content>JSP</body-content>
<attribute>
<name>format</name>
<required>yes</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>

</taglib>

这个标签的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


<%-- Declare tag that we'll use as our helper --%>

<%@ taglib uri="/helpers" prefix="helpers" %>

<html>
<head>
<title>Text Formatting Example</title>
</head>
<body>

<font/>

<%-- Declare bean that will act as our model --%>
<jsp:useBean id="myBean" class="jspbook.ch08.beans.FormattingModel"/>

<jsp:setProperty name="myBean" property="dateValue" value="12/01/01"/>
<jsp:setProperty name="myBean" property="currencyValue" value="23500.253"/>

<%-- Display Formatted Values (using helper) --%>
<center>


<h1>Various Date and Currency Formats</h1>

<br/><br/>
<table cellpadding="5">
<tr>
<th>Format</th>
<th>Original Value</th>
<th>Formatted Value</th>
</tr>
<tr>
<td>Long Date</td>
<td>
<jsp:getProperty name="myBean" property="dateValue"/>
</td>
<td>
<helpers:FormatTag format="date">
<jsp:getProperty name="myBean" property="dateValue"/>
</helpers:FormatTag>
</td>
</tr>
<tr>
<td>Decimal (NN.NN)</td>
<td>${myBean.currencyValue}</td>
<td>
<helpers:FormatTag format="decimal">
${myBean.currencyValue}
</helpers:FormatTag>
</td>
</tr>
<tr>
<td>Integer (N,NNN)</td>
<td>${myBean.currencyValue}</td>
<td>
<helpers:FormatTag format="rounded">
${myBean.currencyValue}
</helpers:FormatTag>
</td>
</tr>
<tr>
<td>Currency (N,NNN.NN)</td>
<td>${myBean.currencyValue}</td>
<td>
<helpers:FormatTag format="currency">
${myBean.currencyValue}
</helpers:FormatTag>
</td>
</tr>
</table>
</center>
</body>
</html>


下图是显示结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐