0

I'm trying to make unexisting pages under my domain go to a 404 page. I need to distinguish 404 pages from the other pages. However, I do not know how to do this. And the thing below is not working.

    @Component(service = Filter.class,
        property = {
            "service.ranking=" + Integer.MIN_VALUE})
    @SlingServletFilter(scope = {SlingServletFilterScope.REQUEST},
        pattern = "/content/foo/.*",
        resourceTypes = "cq:Page",
        extensions = {"html"},
        methods = {"GET"})
    public class NotFoundFilter implements Filter {
    
        private static final String DEFAULT_METHOD = "GET";
    
        @Reference
        private UrlOperationsManager urlOperationsManager;
    
        @Reference
        private RequestResponseFactory requestResponseFactory;
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            if (!(request instanceof SlingHttpServletRequest) ||
                !(response instanceof SlingHttpServletResponse)) {
                chain.doFilter(request, response);
                return;
            }
            
            SlingHttpServletResponse slingResponse = (SlingHttpServletResponse) response;
            //this condition here is not working since slingResponse has no getStatusCode method.
            if(slingResponse.getStatusCode() == 404) {
              //do something
            }
            chain.doFilter(request, response);

    }

    @Override
    public void destroy() {
    }

}
Olaf Kock
  • 46,930
  • 8
  • 59
  • 90
iremenerys
  • 17
  • 6

1 Answers1

0

You could work around this by implementing your own HttpServletResponseWrapper to save the value and access it later. The Sling implementation is marginally different (at least as far as this particular mechanic is concerned) from the generic Servlet API, which is covered in depth in How can I get the HTTP status code out of a ServletResponse in a ServletFilter?

However, if your intention is to serve a particular error document for a given status code, I'd approach it differently. Assuming you use a Dispatcher, you could have the web server take care of it.

The official AEM project archetype comes with a few simple examples that you could enable if you use Apache. The details will depend on your site structure but the gist is that it's possible to provide a similar configuration using the ErrorDocument directive to point to a cached error page relative to the document root, usually making it use content-editable error pages.

Some errors, especially HTTP 5** family could be a bit more tricky that way in that they usually happen when there's something wrong with AEM itself so it's prudent to make sure a fully static version is always available.

toniedzwiedz
  • 17,895
  • 9
  • 86
  • 131