Home / Java Patterns and Pitfalls     frequal.com

Fixing Access For Open Graph And More

The Problem

It is common in full-stack Java apps serving up webapps to use this construct in web.xml so that all URLs get served the SPA root index.jsp:
  <error-page>
    <location>/</location>
  </error-page>
However, this means pages other than the default are served to the web broser with the 404 response code. While human users don't notice, it can cause computer clients to fail to access parts of your site, since they can treat 404 as an error and refuse to process the page.

This is especially noticeable for sites that parse OpenGraph tags. Social media sties, for example, may refuse to load images for subpages that return 404s.

The Fix

Add this to the top of your index.jsp, below %@page:
<% response.setStatus(200); %>
This will force the page to always return a 200 response code, even when served up as an error page. Since for a single-page app, the one page can serve up many URLs that aren't present as individual JSP pages, this is exactly what we want.

Kudos

Thanks to this documentation which showed me this technique.
Last modified on 27 Oct 2024 by AO

Copyright © 2024 Andrew Oliver