How to check for resource file existence at run-time [grails]?

a 夏天 提交于 2019-12-08 05:06:58

问题


I need to test whether a resource file (an image, for instance) exists and if not, I will display another image. My GSP view code looks like:

<% 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')}">
<%}%>

How can I test for a file existence in Grails? What is the code of the method boolean resExists()


回答1:


I found out the answer:

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

or

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

And you call it with resExists('images/img.jpg')




回答2:


I've done the following in 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>

The code below returns the real path of the Grails app:

grailsApplication.mainContext.servletContext.getRealPath("")



回答3:


The above answer did not work for me when used from within a plugin, packaged as a production war. I now use the following:

GrailsConventionGroovyPageLocator groovyPageLocator

def resExists(resPath) {
    def resource = groovyPageLocator.findTemplateByPath(resPath)
    resource
}


来源:https://stackoverflow.com/questions/2089515/how-to-check-for-resource-file-existence-at-run-time-grails

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!