Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot-Angular - Entering Url in Address Bar results in 404

Need help on the basics - I have integrated Angular and Spring Boot. I made production build of the Angular app and copied the 6 files in the Spring boot static resource folder.

By default when I hit localhost:8080 index.html is rendered as Spring boot Automatically registers it as welcome page.

Now when i am inside angular i can navigate to different component via ANGULAR ROUTER and the url is also changing.

But when i copy the same URL for example - localhost:8080/myTask and enter it in url address bar it throws 404 resource not found. Because it hits the Spring controller first and since there is no mapping for that it fails.

like image 788
Arpan Sharma Avatar asked Nov 30 '17 01:11

Arpan Sharma


3 Answers

In the class where you have extended WebMvcConfigurerAdapter in Spring Boot, inside addViewControllers method, you should do something like this

@Override
    public void addViewControllers(final ViewControllerRegistry registry) {
        super.addViewControllers(registry);
      registry.addViewController("/myTask").setViewName("forward:/");
 }

for forwarding, all request, you can do registry.addViewController("/**").setViewName("forward:/");

Update Thanks Jonas for the Suggestion. Since WebMvcConfigurerAdapter is deprecated in Spring 5.0, you can implement the above logic by extending WebMvcConfigurer

like image 62
CGS Avatar answered Oct 23 '22 03:10

CGS


// the perfect solution(from jhipster)
@Controller
public class ClientForwardController {
    @GetMapping(value = "/**/{path:[^\\.]*}")
    public String forward() {
        return "forward:/";
    }
}
like image 33
Mechria Rafik Avatar answered Oct 23 '22 01:10

Mechria Rafik


If you don't use Spring MVC (for example, you are using Jersey), you can also solve this by using a javax.servlet.Filter:

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class AngularRoutingFilter implements Filter {

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
    String requestURI = httpServletRequest.getRequestURI();

    if (shouldDispatch(requestURI)) {
        request.getRequestDispatcher("/").forward(request, response);
    } else {
        chain.doFilter(request, response);
    }
  }

  @Override
  public void init(FilterConfig filterConfig) {}

  @Override
  public void destroy() {}

  private boolean shouldDispatch(String requestURI) {
    /* Exclude/Inlclude URLs here */
    return !(requestURI.startsWith("/api") || requestURI.equals("/"));
  }

}
like image 45
Jacob van Lingen Avatar answered Oct 23 '22 02:10

Jacob van Lingen