三:Using Page Activation Context
Tapestry5 有一个特殊的方式在两个页面间传值。首先,我们需要让这个页面“可激活”,其实就是增加两个方法:onActivate 和onPassivate。在HTTP 请求的生命周期的一个适当的时候Tapestry会调用这两个方法。这样就可以吧@Persist扔一边去了。
为Another.java增加两个方法:
package com.packtpub.t5first.pages;
public class Another
{
private String passedMessage;
public String getPassedMessage()
{
return passedMessage;
}
public void setPassedMessage(String passedMessage)
{
this.passedMessage = passedMessage;
}
void onActivate(String message)
{
System.out.println("Another page is activated! The
message is: " + message);
this.passedMessage = message;
}
String onPassivate()
{
System.out.println("Another page is passivated...");
return passedMessage;
}
}
执行结果:
Setting the message: hi there!
Handling form submission!
Another page is passivated...
Another page is activated! The message is: hi there!
在Start.java中,我们注入了一个Another page 并给它的message属性赋了值。然后我们要求Tepestry展示another page,就象我们前面看到的,通常会销毁这个message(或许是通过我们刚刚放回池里的实例传递的),并且展示了一个新的空的Another page实例,或许是刚刚从池中取出来的。然而,在把第一个实例放回池中之前,Tapestry通过执行onActivate and onPassivate这两个方法去判断Another page是不是在使用激活的上下文。因此Tapestry会调用onPassivate方法,就像这样问一样:“hey,Another page的的实例,有没有什么东东想让我帮你带给‘另一个’你页面的实例,去继续你的工作?”(Hey, instance of the Another page, is there anything you want me to pass to another instance of your page that will continue your work?).
可以从代码中看到,onpassivate方法将报告我们刚才set的message的内容,Tapestry会记得他的回答(注:也就是return的值?)。一旦它使用另一个Another page的实例,它将会在新的实例中作为onActivate 方法参数的形式传递这个储存的值。这样我们就能够看到message属性的值正确的展示在网页上。
但是为什么Tapestry没有创建session却能记得message的值?看看URL:
http://localhost:8080/t5first/another/hi+there%21
当浏览器重定向到Another page的时候这个消息的值已经被记录在URL中,并且Tapestry在没有创建session的情况下可以检索出来。这就意味这,可以保存为书签,在任何时候都可以显示这个值。现在想象用这个还展示一个来自与在线目录的产品,你将会使用激活上下文中收益。
注:这种方式有个致命的缺点,就是传递的参数会在地址看一览无余,对于安全性要求较高的应用,这种方式不适合。