Based on the answers from How to use a servlet filter in Java to change an incoming servlet request url? I ended up with a Spring OncePerRequestFilter.
It checks the incoming URLs whether they are for static resources (by extension) or whether they are calls to the REST api (with /api/
substring) and allows them to be executed as usual. In other cases, it redirects to the /index.html
so Angular's router can handle the request.
public class Html5ModeUrlSupportFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain)
throws ServletException, IOException {
if (isStatic(request) || isApi(request)) {
filterChain.doFilter(request, response);
} else {
request.getRequestDispatcher("/index.html").forward(request, response);
}
}
private boolean isApi(HttpServletRequest request) {
return request.getRequestURI().indexOf("/api/") >= 0;
}
private boolean isStatic(HttpServletRequest request) {
return Pattern.matches(".+\\.((html)|(css)|(js))$", request.getRequestURI());
}
}
Of course, the rules of detecting requests must be adjusted to your needs.