如何在Spring启动的不同URL上从同一目录返回文件?

时间:2017-01-20 20:32:57

标签: angularjs spring spring-mvc spring-boot

我有简单的AngularJS单页面应用程序和后端的Spring Boot。我需要在不同的网址上返回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文件和页面加载。我在index.html文件夹中有resources/public。我认为 localhost:8080/sample/pages 请求会尝试在sample/pages文件夹而不是/中查找资源。我该如何解决这类问题?

1 个答案:

答案 0 :(得分:2)

我会使用自定义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;
                }
            }
        }
    }
}