我可以更新标题栏吗?

时间:2012-05-24 13:13:57

标签: ajax jsf primefaces

在之前的question中,我询问了有关更新菜单栏的问题。 BalusC告诉我,我需要添加包含菜单栏的表单。

我想扩展这个问题,询问我是否可以更新标题中的文字。正在使用模板,我使用

填写值
    <ui:define name="AreaTitle">
        #{viewBacking.current.firstName}  #{viewBacking.current.surName}
    </ui:define>

模板

<h:head>
<title><ui:insert name="AreaTitle">Master template</ui:insert></title>
<link href="style.css" rel="stylesheet" type="text/css" media="screen" />
</h:head>

在标题中定义表单似乎很奇怪,因此没有定义。我在viewBacking.current中设置了一个断点,所以我可以看到它何时使用它。即使我点击刷新以重新显示表单,它也不会再次达到断点。只有当我转到具有不同内容的不同页面时,它才会再次达到断点。刷新的是

public void refreshForm() {
    RequestContext context = RequestContext.getCurrentInstance(); 
    context.update("menuForm:masterMenuBar");
    context.update("AreaTitle");
}

这显示了BalusC在masterMenuBar上给我的上一个解决方案。很可能我不能做我要求做的事,但我想确认是否属实。

谢谢, 伊兰

1 个答案:

答案 0 :(得分:4)

由于<title>不是JSF组件,因此无法通过JSF ajax更新更新标题。您也不能将HTML或JSF组件放在<title>中,这是illegal HTML语法。

您最好的选择是使用JavaScript来更新标题,方法是将其分配给document.title。您可以使用RequestContext#execute()

String fullName = current.getFirstName() + " " + current.getSurName();
context.execute("document.title='" + fullName + "'");

由于这似乎是用户控制的数据,我会使用StringEscapeUtils#escapeJavaScript()来逃避它,以防止潜在的XSS attack holes

String fullName = current.getFirstName() + " " + current.getSurName();
context.execute("document.title='" + StringEscapeUtils.escapeJavaScript(fullName) + "'");

另一种方法是使用OmniFaces <o:onloadScript>

<o:onloadScript>document.title='#{of:escapeJS(viewBacking.current.firstName)} #{of:escapeJS(viewBacking.current.surName)}'</o:onloadScript>

这将在每个ajax请求上重新执行。