【问题标题】:How to check for resource file existence at run-time [grails]?如何在运行时检查资源文件是否存在 [grails]?
【发布时间】:2010-01-18 21:55:36
【问题描述】:

我需要测试资源文件(例如图像)是否存在,如果不存在,我将显示另一个图像。 我的 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()的代码是什么

【问题讨论】:

    标签: spring grails gsp


    【解决方案1】:

    我找到了答案:

    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')调用它

    【讨论】:

    【解决方案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("")
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 你是怎么注入这个的。它总是返回 null 来查找资源
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-09
      • 1970-01-01
      • 1970-01-01
      • 2012-04-02
      • 2022-01-23
      • 1970-01-01
      相关资源
      最近更新 更多