gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 19:01:24 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com