【问题标题】:How to check if an image file exists or not using OGNL?如何使用 OGNL 检查图像文件是否存在?
【发布时间】:2013-07-18 10:57:48
【问题描述】:

我正在创建一个 JSP 页面并使用 OGNL 我想检查目录中是否存在图像文件然后显示它,否则显示空白图像。有什么办法吗?

【问题讨论】:

    标签: java image struts2 ognl


    【解决方案1】:

    在JSP 中,您可以在s:if 标记中创建一个OGNL 表达式并调用返回boolean 的操作方法。例如

    <s:if test="%{isMyFileExists()}">
      <%-- Show the image --%>
    </s:if>
    <s:else>
      <%-- Show blank image --%>
    </s:else>
    

    在行动中

    public class MyAction extends ActionSupport {
    
      private File file;
      //getter and setter here
    
    
      public boolean isMyFileExists throws Exception {
        if (file == null) 
          throw new IllegalStateException("Property file is null");       
        return file.exists();
      }
    }
    

    或者直接使用file属性,如果你添加了公共getter和setter

    <s:if test="%{file.exists()}">
      <%-- Show the image --%>
    </s:if>
    <s:else>
      <%-- Show blank image --%>
    </s:else>
    

    【讨论】:

      【解决方案2】:

      可能有多种方式,但您应该在 Action 中执行此类业务并从 JSP 中仅读取 boolean 结果。或者至少将 File 声明为 Action 属性,通过 Getter 公开它并从 OGNL 调用 .exist() 方法:

      在行动

      private File myFile
      // Getter
      

      在 JSP 中

      <s:if test="myFile.exists()">
      

      仅作记录,其他可能的方式(不用于此目的,只是为了更好地探索OGNL能力):

      1. 从 OGNL 调用静态方法(您需要将 struts.xml 中的 struts.ognl.allowStaticMethodAccess 设置为 true

        <s:if test="@my.package.myUtilClass@doesThisfileExist()" />
        

        在 myUtilClass 中

        public static boolean doesThisFileExist(){
            return new File("someFile.jpg").exists();
        }
        
      2. 或带参数

        <s:if test="@my.package.myUtilClass@doesThisFileExist('someFile.jpg')" />
        

        在 myUtilClass 中

        public static boolean doesThisFileExist(String fileName){
            return new File(fileName).exists();
        }
        
      3. 或者直接在 OGNL 中实例化它

        <s:if test="new java.io.File('someFile.jpg').exists()" />
        

      【讨论】:

        猜你喜欢
        • 2013-01-13
        • 1970-01-01
        • 2016-01-27
        • 1970-01-01
        • 1970-01-01
        • 2011-10-04
        • 2011-02-25
        • 1970-01-01
        • 2014-01-16
        相关资源
        最近更新 更多