第三章 输入验证----tapestry教程Enjoying Web DevelopmenEnjoying Development翻译

第三章 输入验证
这章讲些什么?
这章您将学到如何对用户的输入进行验证,如果需要的话如何显示错误信息。另外您还将学到如何在一个循环里渲染一个组件。

邮资计算器
设想您将开发一个计算器用来计算从某地寄送一个包裹到另一个地方所需要的邮资。用户以千克为单位输入包裹的重量(看下图)。他还可以选择性地输入一个标识他自己的客户代码这样可以得到一定的折扣。点击OK后,它将显示邮资。

为了实现这样一个应用程序,我们先创建一个应用程序,名为Postage,像往常那样设好类路径、输出文件夹和web.xml,然后修改Home.html如下:
<html>
<form jwcid="form">
<table>
<tr>
<td>Weight:</td>
<td><input type="text" jwcid="weight"/></td>
</tr>
<tr>
<td>Patron code:</td>
<td><input type="text" jwcid="patronCode"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit"/></td>
</tr>
</table>
</form>
</html>
在Home.page中定义组件:
<page-specification class="com.ttdev.postage.Home">
<component id="form" type="Form">
<binding name="listener" value="listener:onSubmit"/>
</component>
<component id="weight" type="TextField">
<binding name="value" value="weight"/>
</component>
<component id="patronCode" type="TextField">
<binding name="value" value="patronCode"/>
</component>
</page-specification>
Home.java 像这样:

public abstract class Home extends BasePage {
private Map patronCodeToDiscount;
@InjectPage("Result")
public abstract IPage getResult();
public abstract String getWeight();
public abstract String getPatronCode();
public Home() {
patronCodeToDiscount = new HashMap();
patronCodeToDiscount.put("p1", new Integer(90));
patronCodeToDiscount.put("p2", new Integer(95));
}
public IPage onSubmit() {
int weight = Integer.parseInt(getWeight());
Integer discount = (Integer) patronCodeToDiscount.get(getPatronCode());
int postagePerKg = 10;
int postage = weight * postagePerKg;
if (discount != null) {
postage = postage * discount.intValue() / 100;
}
IPage resultPage = getResult();
PropertyUtils.write(resultPage, "postage", new Integer(postage));
return resultPage;
}
}

接着,创建结果页面,Result.html 像这样
<html>
The postage is <span jwcid="@Insert" value="ognl:postage"/>.
</html>
Result.page 如下:
<page-specification>
<property name="postage"/>
</page-specification>
由于页面类没有指定,BasePage将被使用.Tapestry将创建它的子类来拥有属性.
接下来,在c:/tomcat/conf/Catalina/localhost创建一个上下文描述器Postage.xml:
<Context
docBase="c:/workspace/Postage/context"
path="/Postage"
reloadable="true"/>
现在可以运行这个程序了:

接收整型输入
此刻Home 页面的重量属性是字符型的,这并不好.理想的应该是个整型数. 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值