Execute managebean method from javascript onload event

In theory the following should do it.

<h:body>
    <f:ajax event="load" listener="#{bean.onload}" />
</h:body>

with

public void onload(AjaxBehaviourEvent event) {
    // ...
}

However, this is not supported for some reason. I've ever posted an issue report about that.

The following works, but it's in essence a hack.

<h:head>
    <title>JSF 2.0 onload hack</title>
    <script>
        window.onload = function() {
            document.getElementById('hidden:link').onclick();
        }
    </script>
</h:head>
<h:body>
    <h:form id="hidden" style="display:none">
        <h:commandLink id="link">
            <f:ajax event="click" listener="#{bean.onload}" />
        </h:commandLink>
    </h:form>
</h:body>

If you happen to use PrimeFaces, then you can use its <p:remoteCommand> with autoRun set to true.

<h:body>
    <h:form>
        <p:remoteCommand name="onload" action="#{bean.onload}" autoRun="true" />
    </h:form>
</h:body>

Or if you're using OmniFaces, then you can use its <o:commandScript>

<h:body>
    <h:form>
        <o:commandScript name="onload" action="#{bean.onload}" />
        <h:outputScript target="body">onload()</h:outputScript>
    </h:form>
</h:body>

The <h:outputScript target="body"> renders the <script> in the end of the <body>. The upcoming OmniFaces 2.2 will remove this need by new autorun attribute.

<h:body>
    <h:form>
        <o:commandScript name="onload" action="#{bean.onload}" autorun="true" />
    </h:form>
</h:body>
阅读更多
文章标签: JSF
个人分类: JSF
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Execute managebean method from javascript onload event

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭