Tapestry的每个page需要将引用的图片或CSS写入配置中,比较麻烦,本文提供了一种统一管理各种资源的做法。
一、图片和CSS资源
1,在自定义的ApplicationServlet的init方法中初始化各图片资源:
String path = config.getServletContext().getResource("/").getPath();
path = path.substring(path.indexOf("/") + 1);
path = path.substring(path.indexOf("/"));
GlobalAssets.init(path);
2,在GlobalAssets中:
public static void init(String contextPath) {
GlobalAssets.path = contextPath;//保存环境路径
}
public static IAsset get(String name) {
return new ExternalAsset(GlobalAssets.path + name, null);
}
3,在page里可以引用这些公共图片资源:
<component id="login" type="ImageSubmit">
<binding name="listener" value="listener:loginSubmit"/>
<binding name="image" value="@test.GlobalAssets@get('imgs/login.gif')"/>
</component>
其中绿色部分为应用GlobalAssets的login资源,把login.gif改为login.css即可引用CSS资源。
修订:
1,在BasePage中增加方法getContextAsset
public IAsset getContextAsset(String name) {
Resource rootResource = this.getRequestCycle().getInfrastructure()
.getContextRoot();
Resource resource = rootResource.getRelativeResource(name);
ContextAsset ca = new ContextAsset(this.getRequestCycle()
.getInfrastructure().getContextPath(), resource,
new LocationImpl(resource));
return ca;
}
2,在page文件中引用即可
<component id="login" type="ImageSubmit">
<binding name="listener" value="listener:loginSubmit"/>
<binding name="image" value="getContextAsset('/imgs/login.gif')"/>
</component>
再修订:请参考我的另一篇文章tapestry绑定的研究与应用
二、本地化字符串资源
如果你的应用是MyApp,则在WEB-INF/下创建一个MyApp_zh_CN.properties,其中可以写入:
username=用户名
password=密码
在各个page文件中就可以引用这些中文本地化字符串了。
<component id="username" type="TextField">
<binding name="value" value="username"/>
<binding name="displayName" value="message:username"/>
</component>
其中粗体部分表示引用本地化字符串资源。 |