如何检查 ContextRelativeResource 是否存在?

How to check if ContextRelativeResource exists?

在 Wicket 中,我向页面添加了一个新图像:

String filename = "images/specialLogo.jpg";
add(new Image("logoImage", new ContextRelativeResource(filename)));

如何检查此 "specialLogo.jpg" 文件是否存在,方法是在文件名前添加 应用程序 .war 文件所在的正确路径(ContextRelative)?
换句话说:怎么做:

if (exists) {
  add...(specialLogo)
} else {
  add... (normalLogo)
}

我在 Wicket 项目的测试页面上尝试了这个解决方案。

我们可以为文件名添加上下文,这将是文件的完整路径。 所以(根据您的需要)如果它存在,我们就得到它,否则再拍一张:

String context = ((WebApplication)Application.get()).getServletContext().getContextPath();
String filenameSpecial = "/images/specialLogo.jpg";
String filenameNormal = "/images/normalLogo.jpg";
File f = new File(context + filenameSpecial);
add(new Image("logoImage", new ContextRelativeResource(f.exists() ? filenameSpecial : filenameNormal)));

一种方法是使用 https://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getResource(java.lang.String) 并检查 non-null 结果。

另一种方法是 https://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String),然后使用 File/Path API