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()
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
}
来源:https://stackoverflow.com/questions/2089515/how-to-check-for-resource-file-existence-at-run-time-grails