JS:检查Sling资源是否存在而不创建404错误

时间:2017-10-12 06:35:49

标签: javascript jquery aem cq5 sling

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

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

1 个答案:

答案 0 :(得分: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+"}");
    }
}

以下是一些调用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