1

我需要测试资源文件(例如图像)是否存在,如果不存在,我将显示另一个图像。我的 GSP 视图代码如下所示:

<% if (resExists(dir: "images", file:"img.jpg")) {%>
  <img src="${g.resource(dir:'images',file: 'img.jpg')}">
<% else { %>
  <img src="${g.resource(dir:'images',file: 'noimg.jpg')}">
<%}%>

如何在 Grails 中测试文件是否存在?方法的代码是什么boolean resExists()

4

3 回答 3

2

我找到了答案:

def resExists(resPath)  {
    def resFile = grailsApplication.parentContext.getResource(resPath)
    resFile?.exists()
}

或者

def resExists(resPath)  {
    def resFile = request.servletContext.getResource(resPath)
    resPath
}

你用它来称呼它resExists('images/img.jpg')

于 2010-01-19T00:02:15.347 回答
2

我在 GSP 中做了以下事情:

<g:set var="flag" value="${new File(grailsApplication.mainContext.servletContext.getRealPath("images/sgs-geosol/sign/${sec.username()}.gif")).exists()}"></g:set>

<g:if test="${flag}">

</g:if>

下面的代码返回 Grails 应用程序的真实路径:

grailsApplication.mainContext.servletContext.getRealPath("")
于 2013-06-13T11:35:18.610 回答
1

当从插件中使用时,上述答案对我不起作用,打包为生产战争。我现在使用以下内容:

GrailsConventionGroovyPageLocator groovyPageLocator

def resExists(resPath) {
    def resource = groovyPageLocator.findTemplateByPath(resPath)
    resource
}
于 2013-02-19T16:43:02.173 回答