2013-05-28 126 views
0

爲了我的理解,pageContext可以訪問許多方法,如 getPage,getRequest等。所以,如果直接訪問 ,直接反對使用頁面上下文不是更好嗎?問題 是我不知道你會如何做到這一點。所以說我有這個:Sling - 通過pageContext訪問屬性

public void setProperties(PageContext context){ 
ValueMap properties = (ValueMap) context.getAttribute("properties"); 
Node currentNode = (Node) context.getAttribute("currentNode"); 

pageHeader = properties.get("pageHeader", "") 
} 

這工作正常。你將如何設定你特別需要的?我有 這但它似乎並沒有工作。我只是得到一個**,請檢查是否宣佈的 類型是正確的,如果該方法存在。

Resource resource = requestResolver.getResource("/content/my/resource"); 

public void setProperties(){ 

ValueMap properties = (ValueMap) resource.getAttribute("properties"); 
Node currentNode = (Node) resource.getAttribute("currentNode"); 

} 

回答

1

檢索ValueMap的關鍵是使用Adapter框架並調整適當的資源或節點。 兩者都實現了Adaptable接口,該接口使您能夠調整資源的許多目標類型,如Node,ValueMap等。 http://sling.apache.org/apidocs/sling6/org/apache/sling/api/adapter/Adaptable.html http://sling.apache.org/documentation/the-sling-engine/adapters.html

下面的例子演示如何檢索只讀ValueMap

ValueMap properties = resource.adaptTo(ValueMap.class); 
String propertyValue = values.get("propertyName", String.class); 

如果您需要修改ValueMap的內容,然後去PersistableValueMap。 http://sling.apache.org/apidocs/sling6/org/apache/sling/api/resource/PersistableValueMap.html

PersistableValueMap valueMap = resource.adaptTo(PersistableValueMap.class); 
valueMap.put(key,value); 
valueMap.save(); 
+0

謝謝@Thomas非常有幫助! –