I am developing a backend for an angular application with Spring MVC
It was decided that if the backend receives any request for inexistent paths, or paths that produce application/json and the request does not contain an explicit Accpept: application/json header, the backend should respond with the html that loads the angular application, and let the angular application resolve the path.
After researching how to achieve that in a simple way, my solution was to implement a Spring HandlerInterceptor with the following preHandle
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws ModelAndViewDefiningException {
if (restPath(request) && !acceptJson(request.getHeader(HttpHeaders.ACCEPT))) {
ModelAndView mav = new ModelAndView("/index");
throw new ModelAndViewDefiningException(mav);
}
return true;
}
the restPath() method allows me to filter requests for known paths that do not produce application/json, like static resources or services that produce downloadable files like images, and the acceptJson() method filters the explicit header Accept: application/json
I initially tried to find a way to "forward" the request to another path (instead of a redirect) so that the url on the browser would not change and let the angular application handle it, but could not find a way to do it.
Other ways I read about required me to extend the HttpServletRequest so as to override any method that returns path information and forward with the request dispatcher, but it seemed to hackish and less portable to me.
Can you come up with or is there a more elegant, better or right solution?