Why when I refresh a page in Angular with Java I get an http 404 error?


Fix the 404 error when refreshing the Angular page in a Java application

Angular doesn’t use anymore the # in the URL. When you refresh the page using the URL showed by Angular and not clicking a button in the app, the client router is skipped and the requests goes directly to Java that doesn't know the path of the Single Page Application page.

The solution is to use a fallback route that, in case of missing path on the server side, return the link to the root / home page in Angular.

Angular will get the information about the route and will use his router to show the correct page.

You can implement the soulution using different approaches:

web.xml solution

If you are developing your application with Jakarta EE or Spring the solution is very simple, you don’t have to implement code in your frontend. You can simply add this code snippet in your web.xml


If the page is not found a simple redirection to the frontend page get the work done. The frontend will show the correct page.

Using a @controller

A different approach uses a Spring @controller on the backend. In this example all the links (controllers) of the frontend are prefixed with ‘app’.

The controller receives the request and forward it to the frontend that open the correct page.

package ch.javaee.demo.angular2.web; 
import org.springframework.stereotype.Controller; 
import org.springframework.web.bind.annotation.RequestMapping; 
public class RouterController { 
    public String app() { 
    return "forward:/index.html"; 

Spring Boot config configuration

Another alternative is to tell Spring to redirect all the requests to static to the ROOT URL where Angular can redirect the request.

# Redirect all requests to index.html 

Fullstack Angular / Java application quick start guide.
WebApp built by Marco using SpringBoot 3.2.4 and Java 21. Hosted in Switzerland (GE8).