如何使用OGNL检查图像文件是否存在?

时间:2013-07-19 08:20:04

标签: java struts2 ognl

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

2 个答案:

答案 0 :(得分:0)

在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>

答案 1 :(得分:0)

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

in Action

private File myFile
// Getter
JSP中的

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

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

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

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