Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Spring Boot: How to map my app root (“/”) to index.html?

I'm new to Java and to Spring. How can I map my app root http://localhost:8080/ to a static index.html? If I navigate to http://localhost:8080/index.html its works fine.

My app structure is :

dirs

My config\WebConfig.java looks like this:

@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("/");
        }
}

I tried to add registry.addResourceHandler("/").addResourceLocations("/index.html"); but it fails.

like image 784
Shoham Avatar asked Dec 09 '14 14:12

Shoham


3 Answers

It would have worked out of the box if you hadn't used @EnableWebMvc annotation. When you do that you switch off all the things that Spring Boot does for you in WebMvcAutoConfiguration. You could remove that annotation, or you could add back the view controller that you switched off:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("/").setViewName("forward:/index.html");
}
like image 145
Dave Syer Avatar answered Nov 11 '22 16:11

Dave Syer


An example of Dave Syer's answer:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class MyWebMvcConfig {

    @Bean
    public WebMvcConfigurerAdapter forwardToIndex() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                // forward requests to /admin and /user to their index.html
                registry.addViewController("/admin").setViewName(
                        "forward:/admin/index.html");
                registry.addViewController("/user").setViewName(
                        "forward:/user/index.html");
            }
        };
    }

}
like image 44
justin Avatar answered Nov 11 '22 17:11

justin


if it is a Spring boot App.

Spring Boot automatically detects index.html in public/static/webapp folder. If you have written any controller @Requestmapping("/") it will override the default feature and it will not show the index.html unless you type localhost:8080/index.html

like image 34
Krish Avatar answered Nov 11 '22 15:11

Krish