在AEM SLING servlet中,无法直接使用重定向将请求重定向到内容页面。然而,可以使用Ajax来解决这个问题。以下是一个解决方案的代码示例:
首先,在AEM中创建一个Servlet,用于处理Ajax请求:
package com.example.servlets;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.osgi.service.component.annotations.Component;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import java.io.IOException;
@Component(service = Servlet.class, property = { "sling.servlet.paths=/bin/ajaxredirect" })
public class AjaxRedirectServlet extends SlingAllMethodsServlet {
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
String resourcePath = request.getParameter("resourcePath");
ResourceResolver resourceResolver = request.getResourceResolver();
Resource resource = resourceResolver.getResource(resourcePath);
if (resource != null) {
String contentPath = resource.getPath();
response.getWriter().write(contentPath);
} else {
response.getWriter().write("Resource not found");
}
}
}
在上述示例中,我们创建了一个名为AjaxRedirectServlet的Servlet,用于处理Ajax请求。在doGet方法中,我们获取通过参数传递的资源路径,并使用Sling API获取该资源。如果资源存在,则返回该资源的内容路径。否则,返回"Resource not found"。
然后,在前端使用Ajax请求来调用该Servlet,并处理返回的内容路径:
$.ajax({
url: "/bin/ajaxredirect",
type: "GET",
data: { resourcePath: "/content/mysite/en/homepage" },
success: function(data) {
// 在这里处理返回的内容路径
window.location.href = data;
},
error: function(xhr, status, error) {
console.error(error);
}
});
在上述示例中,我们使用jQuery的$.ajax方法来发送GET请求到AjaxRedirectServlet,并传递资源路径作为参数。在成功回调函数中,我们将返回的内容路径作为新的URL来重定向到内容页面。
注意:在实际使用中,你需要将上述代码示例中的资源路径和Servlet的路径修改为你自己的实际值。