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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.