WebObjects/Web 应用程序/开发/自定义模板
外观
以下解决方案比严格需要的更复杂。它可以避免调试消息,他使用了一些准私有内容。
protected WOElement myTemplate = null;
public WOElement template() {
if ( myTemplate == null ) {
myTemplate = WOComponent.templateWithHTMLString( html, wod, null );
}
return myTemplate;
}
更复杂的方法
这里是一个关于如何覆盖 WOComponent.template() 的小例子,这样你就可以从你想要的地方(例如 jar 文件)加载 html 模板和 wod。
- 首先你需要覆盖 WOComponent.template()
public WOElement template() {
return Component.templateForComponent( this );
}
- 现在,templateForComponent 可以这样写
public static WOElement templateForComponent(WOComponent aComponent) {
{
String aName = aComponent.name();
WOElement anElement = (WOElement) _elementCache.get( aName );
if ( anElement == null ) {
String anHTMLString = Component.componentTemplateWithExtension( aComponent, ".html" );
String aDescriptionString = Component.componentTemplateWithExtension( aComponent, ".wod" );
anElement = WOComponent.templateWithHTMLString ( anHTMLString, aDescriptionString, null );
if ( aComponent.isCachingEnabled() == true ) {
_elementCache.put( aName, anElement );
}
}
return anElement;
}
throw new IllegalArgumentException ( "Component.templateForComponent: null component." );
}
- componentTemplateWithExtension 方法可以写成如下
private static String componentTemplateWithExtension(WOComponent aComponent, String anExtension) {
if ( anExtension != null ) {
String aResource = aComponent.name() + anExtension;
InputStream anInputStream = Component.componentStreamForResource( aComponent, aResource );
if ( anInputStream != null ) {
StringBuffer aBuffer = new StringBuffer();
try {
BufferedInputStream aBufferedStream = new BufferedInputStream( anInputStream );
InputStreamReader aStreamReader = new InputStreamReader( aBufferedStream );
int aChar = -1;
while ( ( aChar = aStreamReader.read() ) != -1 ) {
aBuffer.append( (char) aChar );
}
anInputStream.close();
} catch(Exception anException) {
Log.warning( anException );
}
return aBuffer.toString();
}
throw new RuntimeException ( "Component.componentTemplateWithExtension: resource not found: '" + aResource + "'." );
}
throw new IllegalArgumentException ( "Component.componentTemplateWithExtension: null extension." );
}
}
- 最后,componentStreamForResource 可以写成如下
行
private static InputStream componentStreamForResource(WOComponent aComponent, String aResource) {
if ( aResource != null ) {
File aDirectory = new File( System.getProperty( "user.dir" ) );
File aFile = new File( aDirectory, aResource );
if ( aFile.exists() == true ) {
try {
return new FileInputStream( aFile );
} catch(Exception anException) {
Log.warning( anException);
}
}
return aComponent.getClass().getResourceAsStream( aResource );
}
throw new IllegalArgumentException( "Component.componentStreamForResource: null resource." );
}