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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.