【问题标题】:A ui:include that doesn't throw an error if file not found如果未找到文件,则不会引发错误的 ui:include
【发布时间】:2013-10-14 06:02:58
【问题描述】:

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

编辑

感谢您的所有回答。我正在寻找一种不需要我自己添加所有文件检查逻辑的解决方案。

【问题讨论】:

  • 感谢您到目前为止的回答,我正在寻找一个自动完成而无需编写代码逻辑来检查自己的解决方案。

标签: java html jsf-2 xhtml


【解决方案1】:

您可以使用的解决方法是在呈现页面之前在服务器端使用checking if destination files exist。假设您使用 EL-2.2 which allows parameters 作为视图方法,您可以这样做:

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>

【讨论】:

  • 看起来 ui:include 会抛出 FileNofFound,如果 c:if 验证为 false 的事件...:/
【解决方案2】:

您可以在面板(primefaces)中编写 ui:include
并且仅当您的文件名不为空时才渲染(渲染是面板的属性)。

【讨论】:

  • 类似这样的东西: ttp://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" rel="nofollow" target="_blank">w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> w3.org/1999/xhtml" xmlns: ui="java.sun.com/jsf/facelets" xmlns:p="primefaces.org/ui" xmlns:h="java.sun.com/jsf/html"> 很多其他 html.... 很多其他的 html....
  • fileName 不为空并不能保证具有该名称的文件存在
  • 如果文件不存在也会失败。由于 JSF UIComponents 和 JSTL 标签的循环不同,ui:includeis always evaluated beforerender 属性。 c:if 应该用来代替。
猜你喜欢
  • 2020-02-03
  • 2020-03-28
  • 2020-01-19
  • 2015-09-02
  • 2022-01-20
  • 1970-01-01
  • 1970-01-01
  • 2011-10-16
  • 2018-05-27
相关资源
最近更新 更多