简体   繁体   中英

Keep swagger-ui.html in spring-boot spa application

I have a spring-boot application in which I redirect all resources to index.html , because my front-end is a SPA.

How ever I want to keep the call to localhost:8080/swagger-ui.html the same and overwrite all the others.

It seems that addResourceHandler doesn't work with regular expressions. Any ideas on how to solve this problem ?

import java.io.IOException;

import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.PathResourceResolver;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

        registry.addResourceHandler("/**/*") //^\/[^(api|swagger)].*
                .addResourceLocations("classpath:/public/")
                .resourceChain(true)
                .addResolver(new PathResourceResolver() {
                    @Override
                    protected Resource getResource(String resourcePath, Resource location) throws IOException {
                      Resource requestedResource = location.createRelative(resourcePath);
                      return requestedResource.exists() && requestedResource.isReadable() ? requestedResource : new ClassPathResource("/public/index.html");
                    }
                })
                ;

    }

}

PS: I'm using spring fox with in memory swagger.

You can instead use Spring Controller with @RequestMapping annotation which takes regex path.

//redirects all paths except one containing api or swagger references.
@RequestMapping(value = ""/**/{path:^(?!swagger|api).*}"")
public void redirect(HttpServletResponse response) throws IOException { response.sendRedirect("/"); }

Reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM