2017-10-12 127 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

相关问题