简体   繁体   English

使用Primefaces JavaScript在服务器上的bean上调用JSF方法

[英]Using Primefaces JavaScript to call a JSF method on a bean on the server

In the Primefaces User Guide it shows examples of how to make AJAX calls to the server 在Primefaces用户指南中,它显示了如何向服务器进行AJAX调用的示例

PrimeFaces.ajax.AjaxRequest('/myapp/createUser.jsf',
{
    formId: 'userForm',
    oncomplete: function(xhr, status) {alert('Done');}
});

What I can't figure out is how to call a particular method. 我无法弄清楚的是如何调用特定方法。 My goal is to invalidate the session from the client using JavaScript. 我的目标是使用JavaScript从客户端使会话无效。

RemoteCommand is a nice way to achieve that because it provides you a JavaScript function that does the stuff (calling backing bean, refreshing, submitting a form etc., everything that command link can do). RemoteCommand是一种实现这一目标的好方法,因为它为您提供了一个JavaScript函数来完成这些工作(调用支持bean,刷新,提交表单等,命令链接可以执行的所有操作)。

From PrimeFaces 3.4 documentation : 来自PrimeFaces 3.4文档

<p:remoteCommand name="increment" actionListener="#{counter.increment}"
out="count" />

<script type="text/javascript">
function customFunction() {
    //your custom code
    increment(); //makes a remote call
}
</script>

What I've typically done is put a hidden p:commandLink on the page, then have Javascript call the click() event on it. 我通常做的是在页面上放置一个隐藏的p:commandLink,然后让Javascript调用click()事件。

<p:commandLink id="hiddenLink" 
   actionListener="#{bean.methodToInvoke}" style="display:none"/>

Then 然后

$('#hiddenLink').click();

Do it in the @PostConstruct method of the request scoped bean which is associated with the requsted JSF page by EL like #{bean} . 在请求范围bean的@PostConstruct方法中执行此操作,该方法与EL的请求JSF页面关联,如#{bean}

@ManagedBean
@RequestScoped
public class Bean {

    @PostConstruct
    public void init() {
        // Here.
    }

}

Unrelated to the question, I only wonder why you would ever do it that way? 与这个问题无关,我只想知道为什么你会这样做? JSF/PrimeFaces offers much nicer ways using <f:ajax> and <p:ajax> and consorts. JSF / PrimeFaces使用<f:ajax><p:ajax>和consorts提供了更好的方法。

Is it the intent to run this during Window's unload or beforeunload events? 是否打算在Window的unloadbeforeunload事件期间运行它? If so, then I have to warn you that this is not reliable. 如果是这样,那么我必须警告你,这不可靠。 It's dependent on the browser whether such a request will actually reach the server or not. 依赖于浏览器,这样的请求是否会实际到达服务器。 More than often it won't. 它往往不会。 Use it for pure statistical or premature cleanup purposes only, not for sensitive business purposes. 仅用于纯统计或过早清理目的,不用于敏感业务目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM