Grails 3配置:如何从应用根目录访问图标及磁贴相关文件
解决Grails 3.2.9中根路径静态配置文件的访问问题
我之前在Grails 3.x项目里也遇到过完全一样的问题,浏览器自动查找的这些根路径配置文件(比如browserconfig.xml、site.webmanifest这类),确实没法直接通过asset pipeline搞定,不过有几个简单靠谱的方案:
方案一:直接放到src/main/webapp目录(最推荐)
Grails 3遵循标准的Servlet项目结构,src/main/webapp目录下的文件会被直接部署到应用的根路径,不需要经过asset pipeline处理。你只需要:
- 把
browserconfig.xml、site.webmanifest、safari-pinned-tab.svg,以及各种尺寸的favicon-*.png都复制到src/main/webapp目录下 - 重启应用后,直接访问
http://localhost:8092/site.webmanifest这类路径就能拿到文件了
关于配置文件里的图标路径:比如site.webmanifest里引用的安卓图标,如果你的图标放在grails-app/assets/images里,只需要把路径写成/assets/your-icon.png就行——因为asset pipeline处理后,图片资源会被发布到/assets/路径下,这样配置文件就能正确引用到。
方案二:通过URL映射绑定asset资源(适合不想用webapp目录的情况)
如果更倾向于把这些文件留在grails-app/assets/images目录下,可以修改grails-app/conf/UrlMappings.groovy,给每个文件添加路由映射,把根路径的请求指向对应的asset资源:
class UrlMappings { static mappings = { // 映射根路径的配置文件到asset资源 "/browserconfig.xml" (controller: 'asset', action: 'index', params: [path: 'images/browserconfig.xml']) "/site.webmanifest" (controller: 'asset', action: 'index', params: [path: 'images/site.webmanifest']) "/safari-pinned-tab.svg" (controller: 'asset', action: 'index', params: [path: 'images/safari-pinned-tab.svg']) "/favicon-32x32.png" (controller: 'asset', action: 'index', params: [path: 'images/favicon-32x32.png']) "/favicon-16x16.png" (controller: 'asset', action: 'index', params: [path: 'images/favicon-16x16.png']) // 保留原有路由 "/$controller/$action?/$id?(.$format)?"{ constraints { // apply constraints here } } "/"(view:"/index") "500"(view:'/error') "404"(view:'/notFound') } }
这个方案需要给每个文件单独加映射,虽然麻烦一点,但能让你统一管理所有资源在asset目录下。
验证配置
不管用哪个方案,重启应用后,直接在浏览器地址栏输入对应的根路径URL(比如http://localhost:8092/browserconfig.xml),如果能正常下载或查看文件内容,就说明配置生效了。
内容的提问来源于stack exchange,提问作者Pablo Pazos
相关产品推荐
相关产品推荐

