我正在使用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>
修改
嗨,大家好,感谢所有答案。我正在寻找一种不需要我自己添加所有文件检查逻辑的解决方案。
答案 0 :(得分:5)
在呈现页面之前,您可以在服务器端使用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>
答案 1 :(得分:-1)
您可以在面板(primefaces)中写下 ui:include 仅当fileName不为空时才渲染(渲染是面板的属性)。