java - 用户界面 :include that doesn't throw an error if file not found

标签 java html jsf-2 xhtml

我正在使用 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/

相关文章:

Java:为什么可以在通配符集合上进行转换?

java - 嵌套的 Java 枚举定义 - 声明为静态有什么不同吗?

python - 使用 jinja 标签在 html 标签内使用 if 条件

java - 目标无法到达,标识符 'demoBean' 解析为空

java - 如何在 JSF 中使用应用程序模式

java - 将全局静态变量声明为 null 是一个好习惯吗?

Java Swing 按钮 Action 事件

php - 提交后出现错误结果 IE8 的错误 css

javascript - 在不使用 jQuery 的情况下为 fullCalendar 编写代码时出现错误

jsf - 只处理其值已被修改的输入字段?