【问题标题】:How to return file from same directory on different URL in Spring boot?如何在 Spring Boot 中从不同 URL 上的同一目录返回文件?
【发布时间】:2026-02-05 13:05:01
【问题描述】:

我有简单的 AngularJS 单页应用程序和用于后端的 Spring Boot。我需要在不同的 URL 上返回 index.html。我创建了这种控制器:

@Controller
public class WebResourcesController {

    @RequestMapping(value = {"/sample", "/sample/pages"},  method = RequestMethod.GET)
    public String index() {
        return "index";
    }

}

但对 localhost:8080/sample/pages 的请求返回状态 404。仍然当我向 localhost:8080/sample 发送请求时,我得到了正确的 html 文件和页面加载。我在resources/public 文件夹中有我的index.html。我认为 localhost:8080/sample/pages 请求试图在 sample/pages 文件夹而不是 / 中查找资源。我该如何解决这种问题?

【问题讨论】:

  • 能否给出Class文件的头部(类的注解@RequestMapping)。可以有多个 url 提供相同的内容。 “索引”意味着它将加载 index.html... requestMapping 对文件没有任何操作。

标签: angularjs spring spring-mvc spring-boot


【解决方案1】:

我会使用自定义 PathResourceResolver 配置 WebMvcConfigurerAdapter:

@Configuration
public class SinglePageAppWebMvcConfigurer extends WebMvcConfigurerAdapter
{
    @Autowired
    private ResourceProperties resourceProperties;

    private String apiPath;

    public SinglePageAppWebMvcConfigurer()
    {
    }

    public SinglePageAppWebMvcConfigurer(String apiPath)
    {
        this.apiPath = apiPath;
    }

    protected String getApiPath()
    {
        return apiPath;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        registry.addResourceHandler("/**")
            .addResourceLocations(resourceProperties.getStaticLocations())
            .setCachePeriod(resourceProperties.getCachePeriod()).resourceChain(true)
            .addResolver(new SinglePageAppResourceResolver());
    }

    private class SinglePageAppResourceResolver extends PathResourceResolver
    {
        @Override
        protected Resource getResource(String resourcePath, Resource location) throws IOException
        {
            Resource resource = location.createRelative(resourcePath);
            if (resource.exists() && resource.isReadable()) {
                return resource;
            } else if (getApiPath() != null && ("/" + resourcePath).startsWith(getApiPath())) {
                return null;
            } else {
                LoggerFactory.getLogger(getClass()).info("Routing /" + resourcePath + " to /index.html");
                resource = location.createRelative("index.html");
                if (resource.exists() && resource.isReadable()) {
                    return resource;
                } else {
                    return null;
                }
            }
        }
    }
}

【讨论】:

  • 它的优点在于它是可重复使用的。你可以@Import它进入任何项目。
  • 这样获取其他资源不会有什么问题吗?比如index.module.jsindex.controller.js等不在index所在主目录的文件?
  • 没有,因为是正常获取的。这只是为没有可解析资源的路径返回 index.html 的内容。
最近更新 更多