2017-10-12 128 views
2

我想檢查Sling資源是否已存在。目前我使用CQ.HTTP.get(url)來完成此操作。問題是,如果資源不存在,JS會向控制檯記錄一個404錯誤,我認爲這很醜陋。JS:檢查Sling資源是否存在,但不會創建404錯誤

有沒有更好的方法來檢查是否存在不污染控制檯的資源?

+0

寫你自己的servlet,使其返回具有200狀態的真/假。 – awd

回答

3

下面是一個簡單的servlet,做什麼你問:

/** 
* Servlet that checks if resource exists. 
*/ 
@SlingServlet 
(
    paths = "/bin/exists", 
    extensions = "html", 
    methods = "GET" 
) 
public class ResourceExistsServlet extends SlingSafeMethodsServlet { 

    @Override 
    protected void doGet(final SlingHttpServletRequest request, 
         final SlingHttpServletResponse response) throws ServletException, IOException { 
     // get the resource by the suffix 
     // for example, in the request /bin/exists.htm/apps, "/apps" is the suffix and that's the resource obtained here. 
     Resource resource = request.getRequestPathInfo().getSuffixResource(); 
     // resource is null, does not exist, not null, exists 
     boolean exists = resource != null; 
     // make the response content type JSON 
     response.setContentType(JSONResponse.APPLICATION_JSON_UTF8); 
     // Write the json to the response 
     // TODO: use a library for more complicated JSON, like google's gson. In this case, this string suffices. 
     response.getWriter().write("{\"exists\": "+exists+"}"); 
    } 
} 

這裏是一些樣本JS調用servlet:

// Check if a path exists exists 
function exists(path){ 
    return $.getJSON("/bin/exists.html"+path); 
} 

// check if /apps exists 
exists("/apps") 
.then(function(res){console.log(res.exists)}) 
// prints: true 


// check if /apps123 exists 
exists("/apps123") 
.then(function(res){console.log(res.exists)}) 
// prints: false 
+0

我會建議以下改進: - 使用[org.apache.sling.commons.json.JSONObject](https://sling.apache.org/apidocs/sling7/org/apache/sling/commons/json/JSONObject .html)生成json字符串 - 將擴展名更改爲.json或放棄它,因爲它在設置「路徑」屬性時不起作用 – d33t

+1

該包在AEM 6.3中不再使用 –

+0

這是真的,謝謝您的理解。該圖書館因[法律原因](http://markmail.org/thread/3kx7kkeaksqiduz5)而被棄用,你可以在這裏找到[http://blogs.perficient.com/adobe/2017/08/02/aem -6-3-處理 - 貶低感/)一些替代品。除此之外,問題在於cq5,這是處理json的常見方式。 – d33t

相關問題