Nullpointer
Nullpointer

Reputation: 1086

Spring boot application shows file download option when serving static content

I have a spring boot application in which I have some static files kept inside resources/static directory. One of them is a swagger directory. The file system layout looks as follows:

resources
- static
  - swagger
    - index.html

Now if I send request to my webapp with URI localhost:8080/swagger/index.html then it serves the file correctly. However, if I send request to localhost:8080/swagger then the webapp shows a file download box with an empty binary file named swagger.

In my opinion second URI should actually serve the index.html file automatically. How do I fix this behavior?

Upvotes: 0

Views: 125

Answers (1)

clevertension
clevertension

Reputation: 7077

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

@Configuration
public class WebConfig {
    @Bean
    public WebMvcConfigurerAdapter forwardToIndex() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/swagger").setViewName(
                        "forward:/swagger/index.html");
                registry.addViewController("/swagger/").setViewName(
                        "forward:/swagger/index.html");
            }
        };
    }
}

Upvotes: 1

Related Questions