Home » Java » java – How to serve static pages-Exceptionshub

java – How to serve static pages-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

I need to serve static index.html page from “/” GET request in spring-web.

My module is included into bigger one, packaged as WAR and deployed to tomcat.

I’ve tried

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("WebMvcConfigurer - addResourceHandlers() function get loaded...");
        registry.addResourceHandler("/WEB-INF/classes/index.html")
                .addResourceLocations("/WEB-INF/classes/index.html");
    }
}

and placed index.html in resources folder. Still 404. Can anybody help me out with understanding what have I done wrong?

How to&Answers:

The pattern of the ResourceHandler should reflect the query path, in your case /index.html

Resources inside a jar/war /WEB-INF/classes/ can be accessed via classpath:, in your case classpath:/index.html

So your config should have been like this

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/index.html")
                .addResourceLocations("classpath:/index.html");
    }
}

You can simplify if you have more resources with

registry.addResourceHandler("/*.html")
        .addResourceLocations("classpath:/");