Skip to main content

SpringBoot : How to display static html file in Spring boot MVC application

Points To Remember

  • In order to serve static files like js, css, images etc ,all your files should be under the resources/static folder. Spring application can serve all the static files inside folders
    • resources/static/
    • resources/public/
  • In order to serve html files from spring boot application 
    • your html files should be under static/public folder
    • you need to add view controller to serve html file

How to display static html file in Spring boot MVC application

Step 1 : Extend Class WebMvcConfigurerAdapter




  • You should create a class that extends WebMvcConfigurerAdapter
  • Your class should have @Configuration annotation.
  • You class should not have @EnableMvc annotation.
  • Override addViewControllers method and add your mapping.
  • Override configurePathMatch method and update suffix path matching.

  1. @Configuration  
  2. public class MvcConfigurer extends WebMvcConfigurerAdapter {  
  3.   
  4.     @Override  
  5.     public void addViewControllers(ViewControllerRegistry registry) {  
  6.         registry.addViewController("/error").setViewName("error.html");  
  7.         registry.setOrder(Ordered.HIGHEST_PRECEDENCE);  
  8.     }  
  9.   
  10.     @Override  
  11.     public void configurePathMatch(PathMatchConfigurer configurer) {  
  12.         super.configurePathMatch(configurer);  
  13.         configurer.setUseSuffixPatternMatch(false);  
  14.     }  
  15.   
  16.   
  17. }  


  • In the above code we have added a mapping for "/error" to show "/error.html"
  • Set the registry order to highest precedence, otherwise app will not render the page.
  • Ovveride configurePathMatch to set suffix pattern to false, this will allow /error to render /error.html
NOTE :: Similarly you can add other mappings to display your html pages. To add a default landing page to the application you can add "index.html" under static folder. For index file, you do not need to add any mapping.


Comments