我正在使用 JSF 2。
对于其中一个页面,它需要包含一个符合以下行的页面:
domain/subdomain/cms/[userspecified_code].html
我使用 ui:include 标签来获取这个文件。它适用于存在的文件,但对于不存在的文件,它会抛出 FileNotFoundException 并将整个页面呈现为错误页面。
对于 ui:include 标记是否有替代解决方案跳过/记录文件错误,只显示一个空部分?尽量减少对用户的干扰(包含的文件只是页面的一小部分,如果没有匹配的文件,我宁愿不显示任何东西)。 我能想到的一种方法是加载 ajax 部分,因此如果出现错误,它将是 javascript 错误而不是服务器错误,但是有没有更优雅/更简单的方法呢?
这是我目前拥有的 xhtml:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html">
Lots of other html....
<ui:include src="domain/subdomain/cms/#{userspecified_code}.html"/>
Lots of other html....
</html>
编辑
谢谢大家的回答。我正在寻找一种不需要我自己添加所有文件检查逻辑的解决方案。
最佳答案
您可以使用的解决方法是 checking if destination files exist在呈现页面之前在服务器端。假设您使用的是 EL-2.2 which allows parameters对于 View 方法,您可以这样做:
public boolean fileExists(String fileName)
File file = new File(servletContext.getRealPath("domain/subdomain/cms/"+fileName+".html"));
return file.exists();
}
并使用jSTL条件标签动态包含目标页面:
<c:if test="#{bean.fileExists(userspecified_code)}">
<ui:include src="domain/subdomain/cms/#{userspecified_code}.html" />
</c:if>
此外,为了避免代码重复,您可以使用 fn:join
标记仅对路径求值一次:
<c:if test="#{bean.fileExists(userspecified_code)}">
<ui:include src="#{fn:join('domain/subdomain/cms/',fn:join(userspecified_code,'.html')}" />
</c:if>
关于java - 用户界面 :include that doesn't throw an error if file not found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19354297/