JS:在不产生 404 错误的情况下检查 Sling 资源是否存在

JS: Check if Sling resource exists without creating 404 error

我想检查 Sling 资源是否已经存在。目前我使用 CQ.HTTP.get(url) 来完成这个。问题是,如果资源不存在,JS 会向控制台记录 404 错误,我认为这很丑陋。

有没有更好的方法来检查是否存在不污染控制台的资源?

这是一个简单的 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+"}");
    }
}

下面是一些调用 servlet 的示例 JS:

// 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