我正在创建JSP页面并使用OGNL我想检查目录中是否存在图像文件然后显示它,否则显示空白图像。有没有办法做到这一点?
答案 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能力):
从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();
}
或带参数
<s:if test="@my.package.myUtilClass@doesThisFileExist('someFile.jpg')" />
和myUtilClass
public static boolean doesThisFileExist(String fileName){
return new File(fileName).exists();
}
或直接在OGNL中实例化
<s:if test="new java.io.File('someFile.jpg').exists()" />