【问题标题】:JS: Check if Sling resource exists without creating 404 errorJS:检查 Sling 资源是否存在而不创建 404 错误
【发布时间】:2017-10-12 06:35:49
【问题描述】:

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

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

【问题讨论】:

  • 编写自己的 servlet,使其返回 true/false,状态为 200。

标签: javascript jquery aem sling


【解决方案1】:

这是一个简单的 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

【讨论】:

  • 我建议进行以下改进: - 使用 org.apache.sling.commons.json.JSONObject 生成 json 字符串 - 将扩展名更改为 .json 或删除它,因为在设置“paths”属性时它没有效果
  • 该软件包在 AEM 6.3 中已弃用
  • 确实如此,感谢您指出这一点。由于legal reasons,该库已被弃用,您可以找到here 一些替代方案。除此之外,问题在于 cq5,这是处理 json 的常用方法。
  • 不管怎样,我确实在我的代码中写了一个 todo 来使用像 gson 这样的库来生成 JSON。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-12
相关资源
最近更新 更多