javascript - JS : Check if Sling resource exists without creating 404 error

标签 javascript jquery aem sling

我想检查 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

关于javascript - JS : Check if Sling resource exists without creating 404 error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46702958/

相关文章:

php - 执行 xmlhttprequest 然后定向到新的 url 位置

javascript - 外部脚本缓存

javascript - Jquery 幻灯片菜单 x 滚动问题

aem - 为什么我们在使用 AEM 时扩展 WCMUsePojo 类?

angularjs - 从不同的 JEE 应用程序获取 AEM 创作的模板

javascript - 为什么for循环无法识别||运算符(operator)?

javascript - 数字比较给出错误结果(javascript)

AEM DefaultValue 写入 JCR

javascript - 从列表 Javascript 中动态删除项目

javascript - 使用 jQuery 左右移动