1

Can someone guide me on server rewrite in (AngularJS+spring mvc+tomcat server) app.

Till now I did following settings:

<base href="/Eatery/index.html">
$locationProvider.html5Mode(true);

I don't have web.xml

I am using java configuration in spring mvc

lch
  • 4,569
  • 13
  • 42
  • 75

1 Answers1

4

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.

Community
  • 1
  • 1
fracz
  • 20,536
  • 18
  • 103
  • 149