Java Spring Boot: How to map my app root (โ/โ) to index.html?
Quickly route the root URL /
to index.html
in a Spring Boot app by creating a WebMvcConfigurer and overriding the addViewControllers method. Add a view controller to forward requests to index.html
:
Now we just need to put our index.html
in the right location: src/main/resources/static
. Accessing your app's base URL will now display index.html
.
Preserve your Spring Boot defaults
In Spring Boot, sometimes, less is more. There are a few annotations that one might generously sprinkle around, but might end up causing trouble for auto-configurations. Two such "sneaky" annotations are @RequestMapping("/") and @EnableWebMvc.
The prior, when lurking within your controllers, could override our static mapping, therefore watch out for it.
The latter is notorious for turning off Spring Bootโs auto-configuration and switching to manual mode, letting you define every tiny bit of the configuration, which is needless, in this case.
In short, avoid the Mozarts and let Spring Boot handle resource mapping.
Troubleshooting your mappings
Dodged a bullet with those annotations? ๐ Good, onto the next one.
Static resources can sometimes be a bit sneaky to serve. If you find your mappings not working as expected, directly access index.html
in your browser.
Sounds too simple to be a troubleshooting step, but this will instantly reveal if the issue lies within resource mapping or elsewhere.
Also, remember to keep your Spring Boot version in check, as auto resource mapping of static assets might change with versions.
Redirecting vs Forwarding
In some use cases, you might want to redirect instead of forward. The addRedirectViewController
method in the ViewControllerRegistry
can make that happen:
Sometimes, you might need controller-level handling for the requests:
Remember. The @Configuration
and @EnableWebMvc
annotations are recommended for an explicit MVC setup, especially when you need to customize specific resource locations.
Joining the Java 8+ club? Implement WebMvcConfigurer
instead of extending WebMvcConfigurerAdapter
, which is now as deprecated as floppy disks.
Utilizing Thymeleaf and multiple paths
For those also using Thymeleaf, setting up a @Controller that serves your template is as easy as apple pie:
But remember to place your index.html
in src/main/resources/templates
. Because Spring Boot has got your back with sensible Thymeleaf defaults.
Got more entry points, and each requires a different welcome file? Not a problem! With multiple view controllers, each path can have a unique forward rule:
If you're hosting an API-centric application, try enhancing your API responses with navigational links using Spring HATEOAS, because who doesn't love contextual clues, right?
Was this article helpful?