开发者

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

I need to test whether a resource file (an image, for instanc开发者_StackOverflowe) 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()


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')


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("")


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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜