我想知道为什么我们有“addResourceLocations
”方法,而我们有“addResourceHandler
”方法。
示例:
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
.addResourceLocations("/resources/css/test");
}
在这里,我在调用 addResourceHandler
方法时指定了 "/resources/**"
。然后,我使用 addResourceLocations 方法添加资源位置,这些资源位置应该是我在 addResourceHandler 中指定的 URL 的子文件夹,对吧?那么,为什么 addResourceHandler 本身不足以指定资源位置本身呢?无论如何,它不是位置 URL 的超集吗?
最佳答案
addResourceHandler
接受您将在 View 页面中使用的 URL 模式。
addResourceHandler (java.lang.String... pathPatterns)
Add a resource handler for serving static resources based on the specified URL path patterns. The handler will be invoked for every incoming request that matches to one of the specified path patterns.
另一方面,您可以在 addResourceLocations
中指定资源的实际具体位置。 Spring 将查找此文件夹或位置来解析 url 模式匹配的资源。
addResourceLocations(java.lang.String... resourceLocations)
Add one or more resource locations from which to serve static content. Each location must point to a valid directory. Multiple locations may be specified as a comma-separated list, and the locations will be checked for a given resource in the order specified.
示例
要了解它们之间的差异,请考虑以下示例。如果你配置了
registry.addResourceHandler("/res/**")
.addResourceLocations("/resources/");
然后你可以像这样在你的 View 中使用它们
<link href="res/css/main.css" rel="stylesheet" type="text/css"/>
请注意,您的 ResourceHandler 配置为 URL 模式 res/**
(您可以将其映射到其他内容),并且任何与此模式匹配的资源请求都将被由处理程序处理。
与 res/css/main.css
的请求一样,Spring MVC 会将其与该处理程序进行匹配,并要求该处理程序对其进行解析。然后处理程序将尝试在您配置为 /resources/
的实际资源位置中查找 main.css
文件。
更多内容供阅读
- 方法详细信息 addResourceHandler
- 方法详细信息 addResourceLocations
关于spring - 在 Spring 中提供静态内容 - 为什么我们有 addResourceHandler 时还需要 addResourceLocations 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51873095/