Reputation: 143
I am implementing a custom 404 handler in JSP - AEM, CQ. The file lives in apps/sling/servlet/errorhandler/404.jsp
I am intercepting the request for Not Found and forwarding using RequestDispatcher class.
<%@taglib prefix="sling" uri="http://sling.apache.org/taglibs/sling"%>
<sling:defineObjects />
<%
// setting response code as 404
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
response.setStatus(404);
System.out.println(response.getStatus());
try {
RequestDispatcher rd = request.getRequestDispatcher("/error-page.html");
rd.forward(request, response);
} catch (Exception e) {
RequestDispatcher rd = request.getRequestDispatcher("/error-page.html");
rd.forward(request, response);
}
%>
The above code gets the content of error-page.html keeping the URL same, but the response code sent back is not 404. It is 200 instead.
How can I return a 404?
Upvotes: 1
Views: 4135
Reputation: 1921
Using #include
rather than #forward
will allow you to return a 404:
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
RequestDispatcher dispatcher = request.getRequestDispatcher(path);
dispatcher.include(request,response);
I would suggest creating a Java Servlet rather than using JSP:
@SlingServlet(metatype = true, resourceTypes = {"/apps/sling/servlet/errorhandler"}, extensions = {"404"})
public class ErrorServlet extends SlingSafeMethodsServlet {
@Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
RequestDispatcher dispatcher = request.getRequestDispatcher("myPath");
dispatcher.include(request,response);
}
}
Are you checking for the status code in AEM directly or are you checking after Apache and Dispatcher?
Upvotes: 4