3

I have a Spring Boot hello world for web and some confusion with configuration:

Spring version: 1.2.6.RELEASE

My project structure:

enter image description here

I need to supply some static content so I decided to redefine the source directory for this type of content in some custom WebConfig class (for study purposes):

Javadoc for @EnableWebMvc say:

Adding this annotation to an @Configuration class imports the Spring MVC configuration from WebMvcConfigurationSupport

To customize the imported configuration, implement the interface WebMvcConfigurer or more likely extend the empty method base class WebMvcConfigurerAdapter and override individual methods, e.g.:

So the next configuration-class was born:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/r/**").addResourceLocations("classpath:/static/r/");
        registry.addResourceHandler("/favicon.ico").addResourceLocations("classpath:/static/r/favicon.ico");
    }
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/").setViewName("forward:/r/diploma/index.html");
        registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
        super.addViewControllers(registry);
    }
}

And if run the app and try to visit http://localhost:8080/ I get the next exception:

javax.servlet.ServletException: Could not resolve view with name 'forward:/r/diploma/index.html' in servlet with name 'dispatcherServlet'

But if i remove the @EnableWebMvc from my WebConfig, I got my index.html in browser. So what is the reason of such behavior?

Actually I have a production project which I using as example to study and it has both @EnableWebMvc & WebMvcConfigurerAdapter on WebConfig.

1 Answer 1

6

You should add a ViewResolver to resolves your views in WebConfig, something like this:

@Bean
public InternalResourceViewResolver defaultViewResolver() {
    return new InternalResourceViewResolver();
}

When you're adding @EnableWebMvc, you're turning off all of the spring boot's web auto configurations, which automatically configures such a resolver for you. By removing the annotation, auto configuration will turn on again and the auto configurated ViewResolver solves the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.