Skip to content

Instantly share code, notes, and snippets.

@jnizet
Last active January 9, 2024 15:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnizet/4e4b30961be0496b8350170affcf8b2a to your computer and use it in GitHub Desktop.
Save jnizet/4e4b30961be0496b8350170affcf8b2a to your computer and use it in GitHub Desktop.
Index
import java.io.IOException;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;
/**
* Filter that forwards all GET requests to non-static and non-api resources to index.html. This filter is necessary
* to support deep-linking for URLs generated by the Angular router.
* @author JB Nizet
*/
@Component
@WebFilter("/*")
public class IndexFilter implements Filter {
@Override
public void doFilter(ServletRequest req,
ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
if (mustForward(request)) {
request.getRequestDispatcher("/index.html").forward(request, response);
return;
}
chain.doFilter(request, response);
}
private boolean mustForward(HttpServletRequest request) {
if (!request.getMethod().equals("GET")) {
return false;
}
String fullUri = request.getRequestURI();
String contextPath = request.getContextPath();
String uri = fullUri.substring(contextPath.length());
return !(
uri.equals("")
|| uri.equals("/")
|| uri.startsWith("/api")
|| uri.endsWith(".js")
|| uri.endsWith(".css")
|| uri.startsWith("/index.html")
|| uri.endsWith(".ico")
|| uri.endsWith(".png")
|| uri.endsWith(".jpg")
|| uri.endsWith(".gif")
|| uri.endsWith(".eot")
|| uri.endsWith(".svg")
|| uri.endsWith(".woff2")
|| uri.endsWith(".ttf")
|| uri.endsWith(".woff")
|| uri.endsWith(".json")
|| uri.startsWith("/actuator"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment