【问题标题】:Keep swagger-ui.html in spring-boot spa application在 spring-boot spa 应用程序中保留 swagger-ui.html
【发布时间】:2019-08-06 21:32:45
【问题描述】:

我有一个 spring-boot 应用程序,其中我将所有资源重定向到 index.html,因为我的前端是一个 SPA。

我想如何保持对localhost:8080/swagger-ui.html 的调用不变并覆盖所有其他调用。

addResourceHandler 似乎不适用于正则表达式。关于如何解决这个问题的任何想法?

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:我在内存中使用 spring fox。

【问题讨论】:

    标签: java spring-boot swagger


    【解决方案1】:

    您可以改为使用带有正则表达式路径的 @RequestMapping 注释的 Spring Controller

    //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

    【讨论】:

    • 不要认为请求映射适用于正则表达式:/
    • 是的,你可以在这里找到很多关于 SO 的参考资料。 Example 1.
    • @RequestMapping(value = "^\\/[^(api|swagger)].*") 不起作用,即使正则表达式是正确的。
    • 您的正则表达式不正确,我已使用建议的正则表达式和来自 spring 文档的参考更新了答案以获取更多详细信息和学习。
    • 我提供的解决方案是否解决了您的疑问?你能达到预期的结果吗?请参阅What should I do when someone answers my question?。作为提问者,您有一项特殊的特权:您可以接受您认为是解决问题的最佳解决方案的答案。
    猜你喜欢
    • 2017-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2015-11-18
    相关资源
    最近更新 更多