Mads K
Mads K

Reputation: 837

Spring resourceHandler pattern fails for index-page

I'm trying to map resourceHandlers to resourceLocations in a Spring MVC application, but somehow I can't make the mapping between /* and my index.html work.

@Configuration
@EnableWebMvc
@EnableTransactionManagement(proxyTargetClass = true)
@EnableScheduling
@ComponentScan(basePackages = {"mySpringApp.web.controller"})
public class WebConfig extends WebMvcConfigurerAdapter {

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

    }

    ...

The requests I make returns the following:

Any idea why the index-mapping fails?

Upvotes: 0

Views: 1176

Answers (1)

Alex Minjun Yu
Alex Minjun Yu

Reputation: 3707

When http://localhost:8080/ is requested, spring is looking for a controller with a mapping looking like @RequestMapping("") or @RequestMapping("/"), which you do not have.

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

not serving index file because:
you are simply not specifying what resource you want spring to serve.

possible solutions

  • Write a controller

     @RequestMapping(value = "/")
     public String index() {
         return "redirect:index.html";
     }  
    
  • Refactor addResourceHandlers()

    registry.addResourceHandler("*.html").addResourceLocations("/static/");  
    

Note that addResourceHandler is adding a "pattern" while addResourceLocation is telling spring where exactly/physically to find the requested resource.

Upvotes: 1

Related Questions