一个ui:include如果找不到文件,则不会抛出错误

Jac*_*Dev 3 html java xhtml jsf-2

我正在使用JSF 2.

对于其中一个页面,它需要包含以下行的页面:

domain/subdomain/cms/[userspecified_code].html
Run Code Online (Sandbox Code Playgroud)

我用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>
Run Code Online (Sandbox Code Playgroud)

编辑

嗨,大家好,谢谢你的所有答案.我正在寻找一种不需要我自己添加所有文件检查逻辑的解决方案.

Xtr*_*ica 5

您可以使用的解决方法是在呈现页面之前检查服务器端是否存在目标文件.假设您正在使用允许查看方法参数的 EL-2.2 ,您可以执行以下操作:

public boolean fileExists(String fileName)
    File file = new File(servletContext.getRealPath("domain/subdomain/cms/"+fileName+".html"));
    return file.exists();
}
Run Code Online (Sandbox Code Playgroud)

并使用jstl条件标记动态包含目标页面:

<c:if test="#{bean.fileExists(userspecified_code)}">
    <ui:include src="domain/subdomain/cms/#{userspecified_code}.html" />
</c:if>
Run Code Online (Sandbox Code Playgroud)

此外,为了避免代码重复,您可以使用fn:jointag仅评估路径一次:

<c:if test="#{bean.fileExists(userspecified_code)}">
    <ui:include src="#{fn:join('domain/subdomain/cms/',fn:join(userspecified_code,'.html')}" />
</c:if>
Run Code Online (Sandbox Code Playgroud)